﻿using DevComponents.AdvTree;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.SuperGrid;
using Kimd.Common;
using Kimd.Communication;
using Kimd.Logic;
using Kimd.Machine;
using Kimd.Motion;
using Kimd.Vision;
using Nexus.Windows.Forms;
using SuperTooltip;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI.HtmlControls;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using TCHostUse.Toolkit;
using WorkStation.Common;
using WorkStation.Logic;
using WorkStation.UI.Controls;

namespace WorkStation.UI
{
    public partial class FormHome : Form, IUserChange
    {
        private FormMain _mainForm;
        private FormGRR _grrForm;
        private FormPLC _plcForm;
        private FormRobot _robotForm;
        private FormTester _testerForm;
        public delegate void ChartDelegateAlarmDistribution(Chart chart, List<AlarmDistribution> list);
        public SerializableDictionary<string, int> AlarmDict = new SerializableDictionary<string, int>();
        public Action UpdateMesOPID;
        public FormHome(FormMain mainForm)
        {
            InitializeComponent();
            this._mainForm = mainForm;
        }
        public void UpdateModuleInfo(List<string> moduleNames)
        {
            moduleList2.ModuleNames = moduleNames;
            moduleList2.Update();
            moduleList2.Invalidate();
            List<ButtonX> buttons = moduleList2.GetCircleButtons();
            List<Point> points = moduleList2.GetLocations();
            for (int i = 0; i < buttons.Count; i++)
            {
                buttons[i].Location = points[i];
                this.p_Layout.Controls.Add(buttons[i]);
            }
        }
        private void moduleList1_OnModuleSelected(object sender, EventArgs e)
        {
            string name = (e as ModuleSelectArgs).ModuleName.Split('-')[1];
            _mainForm.Switch2Module();
            _mainForm.ModuleForm.ChangeModuleSelection(name);
        }
        private void AddSampleData()
        {
            // Add sample clients
            aT_Info.Nodes.Add(CreateClientRow("1", "UPH", "0 pcs"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-1", "机械手CT", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-2", "中转站CT", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-3", "前左ArmCT", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-4", "前右ArmCT", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-5", "后左ArmCT", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-6", "后右ArmCT", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-7", "机械手2CT", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-8", "中转站2CT", "0.0 s"));

            #region 节拍时间
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-10", "机械手1取料上料盘", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-12", "精定位1取放料", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-13", "精定位1交互", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-14", "Arm1到精定位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-15", "Arm1放料精定位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-17", "Arm1取料精定位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-18", "Arm1移动到扫码位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-19", "Arm1扫码", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-20", "Arm1移动到治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-21", "Arm1放料治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-22", "Arm1移动治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-23", "Arm1取料治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-24", "Arm1治具到精定位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-25", "Arm2到精定位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-26", "Arm2放料精定位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-28", "Arm2取料精定位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-29", "Arm2移动到扫码位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-30", "Arm2扫码", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-31", "Arm2移动到治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-32", "Arm2放料治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-33", "Arm2移动治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-34", "Arm2取料治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-35", "Arm2治具到精定位", "0.0 s"));

            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-37", "机械手1第一次下料", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-39", "机械手1第二次下料", "0.0 s"));

            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-41", "机械手2取料上料盘", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-43", "精定位2取放料", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-44", "精定位2交互", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-45", "Arm3到精定位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-46", "Arm3放料精定位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-48", "Arm3取料精定位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-49", "Arm3移动到扫码位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-50", "Arm3扫码", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-51", "Arm3移动到治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-52", "Arm3放料治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-53", "Arm3移动治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-54", "Arm3取料治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-55", "Arm3治具到精定位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-56", "Arm4到精定位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-57", "Arm4放料精定位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-59", "Arm4取料精定位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-60", "Arm4移动到扫码位", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-61", "Arm4扫码", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-62", "Arm4移动到治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-63", "Arm4放料治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-64", "Arm4移动治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-65", "Arm4取料治具", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-66", "Arm4治具到精定位", "0.0 s"));

            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-68", "机械手2第一次下料", "0.0 s"));
            aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-70", "机械手2第二次下料", "0.0 s"));
            #endregion
            //aT_Info.Nodes[0].Nodes.Add(CreateClientRow("1-9", "测试站CT", "0.0 s"));
            aT_Info.Nodes[0].ExpandAll();
            aT_Info.Nodes.Add(CreateClientRow("2", "总投入", $"{GlobalVariable.CurrentMachineData.TotalInputCount} pcs"));
            aT_Info.Nodes.Add(CreateClientRow("3", "NG数", $"{GlobalVariable.CurrentMachineData.TotalNGCount} pcs"));
            aT_Info.Nodes.Add(CreateClientRow("4", "OK数", $"{GlobalVariable.CurrentMachineData.TotalOKCount} pcs"));
            aT_Info.Nodes.Add(CreateClientRow("5", "扫码NG数", $"{GlobalVariable.CurrentMachineData.TotalScanNGCount} pcs"));
            aT_Info.Nodes.Add(CreateClientRow("6", "DownTime", $"{GlobalVariable.CurrentMachineData.DownTimes} s"));
            aT_Info.Nodes.Add(CreateClientRow("7", "总产出", $"{GlobalVariable.CurrentMachineData.TotalOutputCount} pcs"));
            aT_Info.Nodes.Add(CreateClientRow("8", "前线CT", $"0 s"));
            aT_Info.Nodes.Add(CreateClientRow("9", "后线CT", $"0 s"));
            aT_Info.Nodes.Add(CreateClientRow("10", "MesNG数", $"{GlobalVariable.CurrentMachineData.TotalMesNGCount} pcs"));
        }
        int logIndex = 0;
        bool colorRev = false;
        public void AddOneLog(MachineMessage message)
        {
            ListViewItem lvi = new ListViewItem(message.StartTime.ToString("HH:mm:ss,fff"));
            //Color.PaleTurquoise : Color.LightCyan
            lvi.SubItems.Add(message.MessageSource);
            lvi.SubItems.Add(message.MessageBody);
            if (message.MessageType == MessageType.Warn ||
                message.MessageType == MessageType.Error ||
                message.MessageType == MessageType.InfoAndPause)
            {
                lvi.ForeColor = Color.OrangeRed;
            }
            else
            {
                lvi.ForeColor = Color.Black;
                if (colorRev)
                    lvi.BackColor = Color.PaleTurquoise;
                else
                    lvi.BackColor = Color.LightCyan;
                colorRev = !colorRev;
            }
            if (this.IsHandleCreated)
            {
                this.BeginInvoke(new Action(() =>
                {
                    lV_Log.Items.Insert(0, lvi);
                    if (lV_Log.Items.Count > 50)
                        lV_Log.Items.RemoveAt(50);
                }));
            }
            //GridRow gridRow = new GridRow();
            //GridCell gridCell1 = new GridCell();
            //gridCell1.Value = message.StartTime.ToString("HH:mm:ss,fff");
            //GridCell gridCell3 = new GridCell();
            //gridCell3.Value = message.MessageSource;
            //GridCell gridCell4 = new GridCell();
            //gridCell4.Value = message.MessageBody;

            //gridRow.Cells.Add(gridCell1);
            //gridRow.Cells.Add(gridCell3);
            //gridRow.Cells.Add(gridCell4);

            //if(message.MessageType == MessageType.Warn || message.MessageType == MessageType.Error)
            //{
            //    gridRow.Cells[0].CellStyles.Default.TextColor = Color.Red;
            //    gridRow.Cells[1].CellStyles.Default.TextColor = Color.Red;
            //    gridRow.Cells[2].CellStyles.Default.TextColor = Color.Red;
            //}

            //this.sGC_Log.PrimaryGrid.Rows.Insert(0, gridRow);
            //if(this.sGC_Log.PrimaryGrid.Rows.Count >= 50)
            //{
            //    this.sGC_Log.PrimaryGrid.Rows.RemoveAt(this.sGC_Log.PrimaryGrid.Rows.Count - 1);
            //}
        }
        public void AddOneWarn(MachineMessage message)
        {
            if (this.IsHandleCreated)
            {
                this.BeginInvoke(new Action(() =>
                {
                    this.l_WarnMethod.Text = message.MessageBody;
                    this.l_WarnMethod.BackgroundStyle.BackColor = Color.IndianRed;
                    this.l_WarnMethod.ForeColor = Color.White;
                }));
            }
        }
        private Node CreateClientRow(string col1, string col2, string col3)
        {
            Node node = new Node(col1);
            node.Cells.Add(new DevComponents.AdvTree.Cell(col2));
            node.Cells.Add(new DevComponents.AdvTree.Cell(col3));
            return node;
        }
        DevComponents.DotNetBar.RadialMenu menuSpeed;
        DevComponents.DotNetBar.RadialMenu menuMode;
        public void createRadialMenu()
        {
            menuSpeed = new DevComponents.DotNetBar.RadialMenu();
            menuSpeed.Location = new Point(l_Speed.Width - 55, 0);
            menuSpeed.Size = new Size(48, 48);
            menuSpeed.Image = Properties.Resources.火箭32;
            menuSpeed.SymbolSize = 14;
            menuSpeed.Diameter = 250; // Make menu diameter larger
            // Handle some events
            //menu.ItemClick += new EventHandler(RadialMenuItemClick);
            //menu.MenuOpened += new EventHandler(RadialMenuOpened);
            //menu.MenuClosed += new EventHandler(RadialMenuClosed);

            RadialMenuItem item = new RadialMenuItem();
            item.Text = "工作速度";
            item.Image = Properties.Resources.火箭32;
            item.Click += Item_Click;
            menuSpeed.Items.Add(item);

            item = new RadialMenuItem();
            item.Text = "调试速度";
            item.Image = Properties.Resources.乌龟32;
            item.Click += Item_Click;
            menuSpeed.Items.Add(item);

            item = new RadialMenuItem();
            item.Text = "试跑速度";
            item.Image = Properties.Resources.兔子32;
            item.Click += Item_Click;
            menuSpeed.Items.Add(item);

            menuSpeed.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.l_Speed.Controls.Add(menuSpeed);

            menuMode = new DevComponents.DotNetBar.RadialMenu();
            menuMode.Location = new Point(this.l_Mode.Width - 55, 0);
            menuMode.Size = new Size(48, 48);
            menuMode.Image = Properties.Resources.生产模式2;
            menuMode.SymbolSize = 14;
            menuMode.Diameter = 250; // Make menu diameter larger
            // Handle some events
            //menu.ItemClick += new EventHandler(RadialMenuItemClick);
            //menu.MenuOpened += new EventHandler(RadialMenuOpened);
            //menu.MenuClosed += new EventHandler(RadialMenuClosed);

            item = new RadialMenuItem();
            item.Text = "生产模式";
            item.Image = Properties.Resources.生产模式2;
            item.Click += Item_Click;
            menuMode.Items.Add(item);

            item = new RadialMenuItem();
            item.Text = "空跑模式";
            item.Image = Properties.Resources.空跑模式2;
            item.Click += Item_Click;
            menuMode.Items.Add(item);

            item = new RadialMenuItem();
            item.Text = "GRR模式";
            item.Image = Properties.Resources.GRR模式2;
            item.Click += Item_Click;
            menuMode.Items.Add(item);

            item = new RadialMenuItem();
            item.Text = "复测模式";
            item.Image = Properties.Resources.复测;
            item.Click += Item_Click;
            menuMode.Items.Add(item);

            item = new RadialMenuItem();
            item.Text = "标定模式";
            item.Image = Properties.Resources.标定模式2;
            item.Click += Item_Click;
            menuMode.Items.Add(item);

            menuMode.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.l_Mode.Controls.Add(menuMode);
        }
        private void SetSpeed()
        {
            foreach (var item in FlowManager.Instance.Flows.Values)
            {
                switch (GlobalVariable.MachineWorkSpeed)
                {
                    case WorkSpeed.Low:
                        item.WorkSpeed = Kimd.Motion.SpeedType.Manual;
                        break;
                    case WorkSpeed.Medium:
                        item.WorkSpeed = Kimd.Motion.SpeedType.TryRun;
                        break;
                    case WorkSpeed.High:
                        item.WorkSpeed = Kimd.Motion.SpeedType.Work;
                        break;
                }
            }
        }
        private void Item_Click(object sender, EventArgs e)
        {
            if ((sender as RadialMenuItem).Text.Equals("工作速度"))
            {
                menuSpeed.Image = Properties.Resources.火箭32;
                GlobalVariable.MachineWorkSpeed = WorkSpeed.High;
                l_Speed.Text = "高速";
                SetSpeed();
            }
            else if ((sender as RadialMenuItem).Text.Equals("调试速度"))
            {
                menuSpeed.Image = Properties.Resources.乌龟32;
                GlobalVariable.MachineWorkSpeed = WorkSpeed.Low;
                l_Speed.Text = "低速";
                SetSpeed();
            }
            else if ((sender as RadialMenuItem).Text.Equals("试跑速度"))
            {
                menuSpeed.Image = Properties.Resources.兔子32;
                GlobalVariable.MachineWorkSpeed = WorkSpeed.Medium;
                l_Speed.Text = "中速";
                SetSpeed();
            }
            else if ((sender as RadialMenuItem).Text.Equals("生产模式"))
            {
                menuMode.Image = Properties.Resources.生产模式2;
                GlobalVariable.MachineWorkMode = WorkMode.Auto;
                GlobalVariable.IsSpotChecking = false;
                GlobalVariable.IsRobotDryRun = false;
                GlobalVariable.IsGrrMode = false;
                GlobalVariable.IsCosmeticMode = false;
                GlobalVariable.IsOnlineRetest = false;
                GlobalVariable.IsDryRun = false;
                l_Mode.Text = "生产";
            }
            else if ((sender as RadialMenuItem).Text.Equals("空跑模式"))
            {
                menuMode.Image = Properties.Resources.空跑模式2;
                GlobalVariable.IsSpotChecking = false;
                GlobalVariable.IsDryRun = true;
                GlobalVariable.IsRobotDryRun = true;
                l_Mode.Text = "空跑";
            }
            else if ((sender as RadialMenuItem).Text.Equals("GRR模式"))
            {
                menuMode.Image = Properties.Resources.GRR模式2;
                GlobalVariable.MachineWorkMode = WorkMode.GRR;
                GlobalVariable.IsSpotChecking = false;
                GlobalVariable.IsRobotDryRun = false;
                GlobalVariable.IsGrrMode = true;
                SystemConfig.Instance.TestParam.IsABBEnable = false;
                l_Mode.Text = "GRR";
                superTabControl2.SelectedTab = sTI_Grr;

                if (_grrForm == null || _grrForm.IsDisposed)
                {
                    _grrForm = new FormGRR();
                    _grrForm.StartPosition = FormStartPosition.CenterScreen;
                    _grrForm.Show();
                }
                else
                {
                    if (_grrForm.WindowState == FormWindowState.Minimized)
                        _grrForm.WindowState = FormWindowState.Normal;
                    _grrForm.BringToFront();
                }
            }
            else if ((sender as RadialMenuItem).Text.Equals("标定模式"))
            {
                menuMode.Image = Properties.Resources.标定模式2;
                GlobalVariable.MachineWorkMode = WorkMode.Calibrate;
                GlobalVariable.IsSpotChecking = false;
                l_Mode.Text = "标定";
            }
            else if ((sender as RadialMenuItem).Text.Equals("复测模式"))
            {
                menuMode.Image = Properties.Resources.复测;
                l_Mode.Text = "复测";
                GlobalVariable.IsSpotChecking = false;

                MessageBoxResult result = MyMessageBoxEx.ShowBox("确定进入 在线复测 模式吗?", "清料", new List<string>() { "确定", "取消" }, MessageBoxType.Info);
                if (result == MessageBoxResult.First)
                {
                    GlobalVariable.IsOnlineRetest = true;
                }
                else if (result == MessageBoxResult.Third)
                {
                    GlobalVariable.IsOnlineRetest = false;
                }
                else if (result == MessageBoxResult.Cancel)
                    return;
                timecount2 = 0;
            }
        }
        List<ButtonX> buttons = new List<ButtonX>();
        List<Label> testerEnableStatusLabels = new List<Label>();
        private void FormHome_Load(object sender, EventArgs e)
        {
            UpdateModuleInfo(MachineResource.Instance.GetAllModuleNames());
            createRadialMenu();
            AddSampleData();
            initWarnChart();

            // Creates wrapper to provide SuperTooltip control access to the node object
            NodeSuperTooltipProvider sp = new NodeSuperTooltipProvider(l_WarnMethod);
            l_WarnMethod.Tag = sp;
            // Assign the wrapper to SuperTooltip control together with information
            // about what to display on Super Tooltip for this node.
            superTooltip1.SetSuperTooltip(sp,
                new DevComponents.DotNetBar.SuperTooltipInfo("报警后处理方式", "",
                                                             "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.\r\n\r\nzzzzzzzzzzzzz" + "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv",
                                                             null, null,
                                                             DevComponents.DotNetBar.eTooltipColor.Teal, true, false, new System.Drawing.Size(0, 0)));
            l_Mode.Text = "生产";
            l_Speed.Text = "高速";

            //UpdateCount("Input", GlobalVariable.CurrentMachineData.TotalInputCount.ToString());
            //UpdateCount("OK", GlobalVariable.CurrentMachineData.TotalOKCount.ToString());

            foreach (var item in MachineResource.Instance.MachineAxis.Values)
            {
                GridRow gridRow = new GridRow();

                gridRow.Tag = item;

                GridCell gridCell1 = new GridCell();
                gridCell1.Value = item.Description;
                GridCell gridCell3 = new GridCell();
                gridCell3.Value = item.LastPosition;

                gridRow.Cells.Add(gridCell1);
                gridRow.Cells.Add(gridCell3);


                this.sGC_AxisPausePosition.PrimaryGrid.Rows.Add(gridRow);
            }
            UpdateWarnStatics();

            nUD_Time1.Value = SystemConfig.Instance.GetProductVacDelay;
#if FCT
            this.p_Tray.Visible = true;
            //EmbeddedExeTool exetool = new EmbeddedExeTool();
            //string path = "\"" + Environment.CurrentDirectory + "\\Interactive\\Interactive.exe" + "\""; //debug下面的文件夹
            //exetool.LoadEXE(this.panel2, path);
            this.p_Layout.Visible = true;
            this.p_Tray.Visible = false;
#else
            this.p_Layout.Visible= true;
            this.p_Tray.Visible = false;
#endif

            testerEnableStatusLabels.Add(l_Tester1);
            testerEnableStatusLabels.Add(l_Tester2);
            testerEnableStatusLabels.Add(l_Tester3);
            testerEnableStatusLabels.Add(l_Tester4);
            testerEnableStatusLabels.Add(l_Tester5);
            testerEnableStatusLabels.Add(l_Tester6);
            testerEnableStatusLabels.Add(l_Tester7);
            testerEnableStatusLabels.Add(l_Tester8);
            testerEnableStatusLabels.Add(l_Tester9);
            testerEnableStatusLabels.Add(l_Tester10);
            testerEnableStatusLabels.Add(l_Tester11);
            testerEnableStatusLabels.Add(l_Tester12);
            GlobalVariable.OnSingleRunPause += OnPauseAction;
        }

        private void OnPauseAction()
        {
            if (SystemConfig.Instance.UsingStatus.IsSingleRunMode)
            {
                FlowManager.Instance.Pause();
                this.Invoke(new Action(() => { this.btn_Start.Enabled = true; }));
                MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, "暂停", "系统", 0, "系统"));
                GlobalVariable.ColorLight.Pause();
                GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人程序启动] = false;
                GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人停止] = false;
                GlobalVariable.RobotControlStatus2[(int)RobotoutEnumRobot2.机器人程序启动] = false;
                GlobalVariable.RobotControlStatus2[(int)RobotoutEnumRobot2.机器人停止] = false;
            }
        }

        public void UpdateFlowStatus()
        {
            foreach (var item in FlowManager.Instance.Flows)
            {
                TabPage tabPage = new TabPage();
                tabPage.Text = item.Key;
                AdvPropertyGrid apg = new AdvPropertyGrid();
                apg.SelectedObject = item.Value.Status;
                apg.Dock = DockStyle.Fill;
                tabPage.Controls.Add(apg);
                this.tC_FlowStatus.TabPages.Add(tabPage);
            }
        }
        public void InitTrayUI(DrawingBoard board, Tray tray, string imageName,
            int cellWidth, int cellHeight, int offsetX, int offsetY, bool isReverse = false)
        {
            board.IsShowDescription = false;
            tray.CellWidth = cellWidth;
            tray.CellHeight = cellHeight;
            tray.CellOffsetX = offsetX;
            tray.CellOffsetY = offsetY;
            tray.CreateRectangles(isReverse);
            board.CreatedShapes.Clear();
            tray.CellShapes.ForEach(s => board.CreatedShapes.Add(s));
            board.OriginalImage = DrawingBoard.Bmp2HalconImage(new Bitmap(Application.StartupPath + $"\\Images\\{imageName}.png"));
        }
        private void initWarnChart()
        {
            //if (File.Exists(@"D:\Alarm.xml"))
            //{
            //    AlarmDict = XmlSerializerHelper<SerializableDictionary<string, int>>.DeserializeFromFile(@"D:\Alarm.xml");
            //}

            //AlarmDict.Add("吸嘴1吸真空报警", 3);
            //AlarmDict.Add("吸嘴2吸真空报警", 6);
            //AlarmDict.Add("X轴伺服报警", 4);

            //this.chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = System.Drawing.Color.Transparent;
            //this.chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = System.Drawing.Color.Transparent;

            //Dictionary<string, int> descSortByValue = DescSortByValue(AlarmDict);
            //List<AlarmDistribution> alarmDistributions = new List<AlarmDistribution>();
            //foreach (KeyValuePair<string, int> kvp in descSortByValue)
            //{
            //    alarmDistributions.Add(new AlarmDistribution() { AlarmName = kvp.Key, AlarmNum = kvp.Value });
            //}
            //if (this.InvokeRequired)
            //{
            //    this.Invoke(new MethodInvoker(() =>
            //    {
            //        // 年龄分布
            //        this.chart1.BeginInvoke(new ChartDelegateAlarmDistribution(ChartAlarmDistributionMethod), this.chart1, alarmDistributions);
            //    }));
            //}
            //else
            //{
            //    // 年龄分布
            //    this.chart1.BeginInvoke(new ChartDelegateAlarmDistribution(ChartAlarmDistributionMethod), this.chart1, alarmDistributions);
            //}
        }

        int _oringWidth = 0;
        int _oringHeight = 0;
        bool _isLoaded = true;
        private void panelEx9_Resize(object sender, EventArgs e)
        {
            if (_isLoaded)
            {
                _isLoaded = false;
                _oringWidth = p_Layout.Width;
                _oringHeight = p_Layout.Height;
            }
            moduleList2.RelocateCircleButtons(_oringWidth, _oringHeight, this.p_Layout.Width, this.p_Layout.Height);
        }
        private bool isDoorOpen()
        {
            return !MachineResource.Instance.MachineSensor["前门禁1"].WaitOn() ||
                   !MachineResource.Instance.MachineSensor["前门禁2"].WaitOn() ||
                   !MachineResource.Instance.MachineSensor["前门禁3"].WaitOn() ||
                   !MachineResource.Instance.MachineSensor["前门禁4"].WaitOn() ||
                   !MachineResource.Instance.MachineSensor["后门禁1"].WaitOn() ||
                   !MachineResource.Instance.MachineSensor["后门禁2"].WaitOn() ||
                   !MachineResource.Instance.MachineSensor["后门禁3"].WaitOn() ||
                   !MachineResource.Instance.MachineSensor["后门禁4"].WaitOn();
        }
        private bool isSafeLightOpen(bool isFront)
        {
            if (isFront)
            {
                return !MachineResource.Instance.MachineSensor["前门光栅1"].WaitOn() ||
                                  !MachineResource.Instance.MachineSensor["前门光栅2"].WaitOn();
            }
            else
            {
                return !MachineResource.Instance.MachineSensor["后门光栅1"].WaitOn() ||
                                    !MachineResource.Instance.MachineSensor["后门光栅2"].WaitOn();
            }
        }
       
        bool _firstTimeRun = true;
        bool _systemAlreadyRun = false;
        private async void ControlButton_Click(object sender, EventArgs e)
        {
            if ((sender as ButtonX).Name.Equals("btn_Start"))
            {
                if (MachineResource.Instance.MachineSensor.ContainsKey("设备急停") && !MachineResource.Instance.MachineSensor["设备急停"].WaitOn())
                {
                    SystemInfo.ShowToastInfo(panelEx6, "急停按下", true, 3);
                    return;
                }
                if (!GlobalVariable.IsSystemAlreadyHome)
                {
                    SystemInfo.ShowToastInfo(panelEx6, "系统尚未进行原点复归,请复归后继续...", true, 3);
                    return;
                }
                if (GlobalVariable.IsSystemErr)
                {
                    SystemInfo.ShowToastInfo(panelEx6, "系统报警中...请先进行报警复位后继续...", true, 3);
                    return;
                }
                if (MachineResource.Instance.MachineSensor.ContainsKey("前门禁1"))
                {
                    if ((isDoorOpen()) && GlobalVariable.IsSafeDoorCheck)
                    {
                        SystemInfo.ShowToastInfo(panelEx6, "安全门被打开", true, 3);
                        return;
                    }
                }
                if (MachineResource.Instance.MachineSensor.ContainsKey("前门光栅1"))
                {
                    if ((isSafeLightOpen(true)) && !SystemConfig.Instance.UsingStatus.IsFrontDisable)
                    {
                        SystemInfo.ShowToastInfo(panelEx6, "前线光栅触碰", true, 3);
                        return;
                    }
                    if ((isSafeLightOpen(false)) && !SystemConfig.Instance.UsingStatus.IsBackDisable)
                    {
                        SystemInfo.ShowToastInfo(panelEx6, "后线光栅触碰", true, 3);
                        return;
                    }
                }
                
                if (_firstTimeRun)
                {
                    //if (!GlobalVariable.HasNotifyRobotSwitch)
                    //{
                    //    SystemInfo.ShowToastInfo(this, "当前尚未通知机械手切换产品完成，请切换正确产品后重新回原!", true, 3);
                    //    return;
                    //}
                    _firstTimeRun = false;
                    if (GlobalVariable.MachineWorkMode == WorkMode.Calibrate)
                    {
                        foreach (var item in FlowManager.Instance.Flows.Values)
                        {
                            item.WorkMode = FlowMode.Calibrate;
                        }
                    }
                    //else if (GlobalVariable.MachineWorkMode == WorkMode.SpotCheck)
                    //{
                    //    foreach (var item in FlowManager.Instance.Flows.Values)
                    //    {
                    //        item.WorkMode = FlowMode.SpotCheck;
                    //    }
                    //}
                    else
                    {
                        foreach (var item in FlowManager.Instance.Flows.Values)
                        {
                            item.WorkMode = FlowMode.Auto;
                        }
                    }
                    string errInfo = "";
                    FlowManager.Instance.Init(out errInfo);
                    if (!string.IsNullOrEmpty(errInfo))
                    {
                        SystemInfo.ShowToastInfo(this, errInfo, true);
                        return;
                    }
                }
                //系统已经自动运行过，再次启动时，需要检测各电机位置是否再最后一次运行的时候
                if (_systemAlreadyRun)
                {
                    string errInfo = "";
                    if (!checkAllAxisInLastPosition(out errInfo) && false)
                    {
                        SystemInfo.ShowToastInfo(this, errInfo, true);
                        return;
                    }
                }
                //判断下测试Mes状态
                if (SystemConfig.Instance.MesParam.EnableMES)
                {
                    if (!SystemConfig.Instance.UsingStatus.IsFrontDisable)
                    {
                        if (!GlobalVariable.TestMesEnable1)
                        {
                            SystemInfo.ShowToastInfo(panelEx6, "测试机Mes1未打开，请打开！", true, 3);
                            return;
                        }
                    }
                    if (!SystemConfig.Instance.UsingStatus.IsBackDisable)
                    {
                        if (!GlobalVariable.TestMesEnable2)
                        {
                            SystemInfo.ShowToastInfo(panelEx6, "测试机Mes2未打开，请打开！", true, 3);
                            return;
                        }
                    }

                }
                else
                {
                    if (!SystemConfig.Instance.UsingStatus.IsFrontDisable)
                    {
                        if (GlobalVariable.TestMesEnable1)
                        {
                            SystemInfo.ShowToastInfo(panelEx6, "测试机Mes1已打开，请关闭！", true, 3);
                            return;
                        }
                    }
                    if (!SystemConfig.Instance.UsingStatus.IsBackDisable)
                    {
                        if (GlobalVariable.TestMesEnable2)
                        {
                            SystemInfo.ShowToastInfo(panelEx6, "测试机Mes2已打开，请关闭！", true, 3);
                            return;
                        }
                    }
                }
                //开启机械手通信
                GlobalVariable.RobotCommDisable = false;
                #region DownTime计算
                if (GlobalVariable.IsDownTimeFlag)
                {
                    GlobalVariable.IsDownTimeFlag = false;
                    GlobalVariable.DownTimeMonitor.Stop();
                    GlobalVariable.CurrentMachineData.DownTimes += GlobalVariable.DownTimeMonitor.ElapsedMilliseconds / 1000.0;
                    MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Count, GlobalVariable.CurrentMachineData.DownTimes.ToString(), "系统", 0, "DownTime"));
                }
                #endregion
                MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, "启动", "系统", 0, "系统"));
                FlowManager.Instance.Start();
                FlowManager.Instance.IsRunFalg = true;
                GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人停止] = true;
                if (GlobalVariable.RobotStatus[(int)RobotinEnumRobot1.机器人警报状态])
                {
                    GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人报警复位] = true;
                    GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人停止] = false;
                    Thread.Sleep(200);
                    GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人停止] = true;
                    Thread.Sleep(50);
                    GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人程序启动] = true;
                }
                else
                {
                    GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人报警复位] = true;
                    GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人程序启动] = true;
                }

                GlobalVariable.RobotControlStatus2[(int)RobotoutEnumRobot2.机器人停止] = true;
                if (GlobalVariable.RobotStatus2[(int)RobotinEnumRobot2.机器人警报状态])
                {
                    GlobalVariable.RobotControlStatus2[(int)RobotoutEnumRobot2.机器人报警复位] = true;
                    GlobalVariable.RobotControlStatus2[(int)RobotoutEnumRobot2.机器人停止] = false;
                    Thread.Sleep(200);
                    GlobalVariable.RobotControlStatus2[(int)RobotoutEnumRobot2.机器人停止] = true;
                    Thread.Sleep(50);
                    GlobalVariable.RobotControlStatus2[(int)RobotoutEnumRobot2.机器人程序启动] = true;
                }
                else
                {
                    GlobalVariable.RobotControlStatus2[(int)RobotoutEnumRobot2.机器人报警复位] = true;
                    GlobalVariable.RobotControlStatus2[(int)RobotoutEnumRobot2.机器人程序启动] = true;
                }
                this.btn_Start.Enabled = false;
                this.btn_Pause.Enabled = true;
                this.btn_Stop.Enabled = true;
                this.btn_Home.Enabled = false;
                GlobalVariable.ColorLight.Run();
                //系统有过运行后，该标志位始终为true
                _systemAlreadyRun = true;
                GlobalVariable.IsReadyForCheck = false;
            }
            else if ((sender as ButtonX).Name.Equals("btn_Stop"))
            {
                if (MessageBox.Show("确定要停止全流程吗?", "停止", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                {
                    GlobalVariable.HasNotifyRobotSwitch = false;
                    ResetSignalToPLC();
                    _mainForm.Stopping();
                    FlowManager.Instance.Stop();
                    this.btn_Home.Enabled = false;
                    this.btn_Pause.Enabled = false;
                    this.btn_Start.Enabled = false;
                    this.btn_Stop.Enabled = false;
                    #region DownTime计算
                    if (GlobalVariable.IsDownTimeFlag)
                    {
                        GlobalVariable.IsDownTimeFlag = false;
                        GlobalVariable.DownTimeMonitor.Stop();
                        GlobalVariable.CurrentMachineData.DownTimes += GlobalVariable.DownTimeMonitor.ElapsedMilliseconds / 1000.0;
                        MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Count, GlobalVariable.CurrentMachineData.DownTimes.ToString(), "系统", 0, "DownTime"));
                    }
                    #endregion
                    MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, "停止", "系统", 0, "系统"));
                    btn_Stop.Enabled = btn_Home.Enabled = await Task.Run(() =>
                    {
                        while (!FlowManager.Instance.AllFlowStopped)
                        {
                            Thread.Sleep(2);
                        }
                        return true;
                    });
                    _mainForm.Stopped();
                    AllModuleReset();
                    _firstTimeRun = true;
                    GlobalVariable.IsSystemErr = false;
                    //GlobalVariable.IsSystemAlreadyHome = false;
                    //Stop后，方可进行回零动作
                    this.btn_Home.Enabled = true;
                    GlobalVariable.ColorLight.Stop();
                    GlobalVariable.IsClearFinish = false;
                }
            }
            else if ((sender as ButtonX).Name.Equals("btn_Pause"))
            {
                #region DownTime计算
                if (FlowManager.Instance.IsRunFalg)
                {
                    if (!GlobalVariable.IsDownTimeFlag)
                    {
                        GlobalVariable.IsDownTimeFlag = true;
                        GlobalVariable.DownTimeMonitor.Restart();
                    }
                }
                #endregion
                FlowManager.Instance.Pause();
                this.btn_Start.Enabled = true;
                //his.btn_Pause.Enabled = false;
                //this.btn_Home.Enabled = false;
                //btn_Start.Enabled = btn_Stop.Enabled = await Task.Run(() =>
                //{
                //    while (!FlowManager.Instance.AllFlowPaused)
                //    {
                //        Thread.Sleep(2);
                //    }
                //    return true;
                //});
                MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, "暂停", "系统", 0, "系统"));
                GlobalVariable.ColorLight.Pause();
                GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人程序启动] = false;
                GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人停止] = false;
                GlobalVariable.RobotControlStatus2[(int)RobotoutEnumRobot2.机器人程序启动] = false;
                GlobalVariable.RobotControlStatus2[(int)RobotoutEnumRobot2.机器人停止] = false;
            }
            else if ((sender as ButtonX).Name.Equals("btn_Home"))
            {
                if (MachineResource.Instance.MachineSensor.ContainsKey("设备急停") && !MachineResource.Instance.MachineSensor["设备急停"].WaitOn())
                {
                    SystemInfo.ShowToastInfo(panelEx6, "急停按下", true, 3);
                    return;
                }
                if (GlobalVariable.IsSystemErr)
                {
                    SystemInfo.ShowToastInfo(panelEx6, "系统报警中...请先进行报警复位后继续...", true, 3);
                    return;
                }
                if (MachineResource.Instance.MachineSensor.ContainsKey("前门禁1"))
                {
                    if ((isDoorOpen()) && GlobalVariable.IsSafeDoorCheck)
                    {
                        SystemInfo.ShowToastInfo(panelEx6, "安全门被打开", true, 3);
                        return;
                    }
                }
                if (MachineResource.Instance.MachineSensor.ContainsKey("前门光栅1"))
                {
                    if ((isSafeLightOpen(true)) && !SystemConfig.Instance.UsingStatus.IsFrontDisable)
                    {
                        SystemInfo.ShowToastInfo(panelEx6, "前线光栅触碰", true, 3);
                        return;
                    }
                    if ((isSafeLightOpen(false)) && !SystemConfig.Instance.UsingStatus.IsBackDisable)
                    {
                        SystemInfo.ShowToastInfo(panelEx6, "后线光栅触碰", true, 3);
                        return;
                    }
                }
                if (GlobalVariable.IsSystemHoming)
                {
                    FlowManager.Instance.Start();
                }
                else
                {
                    if (!FlowManager.Instance.AllFlowStopped)
                    {
                        SystemInfo.ShowToastInfo(panelEx6, "系统运行中...请先停止再进行原点复归", true, 3);
                        return;
                    }
                    foreach (var item in MachineResource.Instance.MachineAxis.Values)
                    {
                        foreach (var limit in item.SensorLimits)
                        {
                            limit.IsEnable = true;
                        }
                        foreach (var limit in item.PositionLimits)
                        {
                            limit.IsEnable = true;
                        }
                        foreach (var limit in item.AxisLimits)
                        {
                            limit.IsEnable = true;
                        }
                    }
                    GlobalVariable.ColorLight.Home();
                    _mainForm.Homing();
                    this.btn_Home.Enabled = false;
                    this.btn_Pause.Enabled = true;
                    this.btn_Start.Enabled = false;
                    this.btn_Stop.Enabled = true;
                    //GlobalVariable.IsSystemAlreadyHome = false;
                    foreach (var item in FlowManager.Instance.Flows.Values)
                    {
                        item.WorkMode = FlowMode.Home;
                        item.Status.IsHomeFinish = false;
                    }
                    string errInfo = "";
                    FlowManager.Instance.ResetAllSignalBreak();
                    FlowManager.Instance.Init(out errInfo);
                    if (!string.IsNullOrEmpty(errInfo))
                    {
                        //SystemInfo.ShowToastInfo(this, errInfo, true);
                        MessageBox.Show(errInfo, "初始化错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.btn_Home.Enabled = true;
                        return;
                    }
                    MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, "回原", "系统", 0, "系统"));
                    FlowManager.Instance.Start();
                    GlobalVariable.IsSystemHoming = true;
                    GlobalVariable.DownTimeMonitor.Stop();
                    GlobalVariable.IsDownTimeFlag = false;
                    btn_Home.Enabled = btn_Stop.Enabled = await Task.Run(() =>
                    {
                        while (!FlowManager.Instance.AllFlowHomeFinished && !FlowManager.Instance.IsBreak())
                        {
                            Thread.Sleep(2);
                        }
                        if (!FlowManager.Instance.IsBreak())
                        {
                            FlowManager.Instance.Pause();
                            GlobalVariable.IsSystemAlreadyHome = true;
                            this.BeginInvoke(new Action(() =>
                            {
                                btn_Start.Enabled = true;
                                _mainForm.HomeFinished();
                                this.l_Clear.BackgroundStyle.BorderWidth = 0;
                                this.l_Clear.BackgroundStyle.BackColor = Color.DeepSkyBlue;
                                this.l_SpotCheck.BackgroundStyle.BorderWidth = 0;
                                this.l_SpotCheck.BackgroundStyle.BackColor = Color.LightGreen;
                            }));

                            //if (MessageBox.Show("原点复归完成,确认是否开Mes?，‘Yes’：打开Mes,‘NO’：关闭Mes", "回原", MessageBoxButtons.YesNo, MessageBoxIcon.Information)
                            //    == DialogResult.Yes)
                            //{
                            //    SystemConfig.Instance.MesParam.EnableMES = true;
                            //    MesSendSts(true);
                            //    MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, "原点复归完成,人员选择开启Mes", "系统", 0, "系统"));
                            //}
                            //else
                            //{
                            //    SystemConfig.Instance.MesParam.EnableMES = false;
                            //    MesSendSts(false);
                            //    MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, "原点复归完成,人员选择关闭Mes", "系统", 0, "系统"));
                            //}
                            GlobalVariable.IsClearLater = false;
                            GlobalVariable.IsClearNow = false;
                            GlobalVariable.IsClearLater2 = false;
                            GlobalVariable.IsClearNow2 = false;
                            GlobalVariable.IsClearFinish = false;

                            GlobalVariable.RightFinishSpotCheck = false;
                            GlobalVariable.LeftFinishSpotCheck = false;
                            GlobalVariable.NowSpotCheckMode = false;
                            GlobalVariable.IsReadyForCheck = true;
                            _systemAlreadyRun = false;
                        }
                        else
                            GlobalVariable.IsSystemAlreadyHome = false;
                        GlobalVariable.IsSystemHoming = false;
                        GlobalVariable.TotalGrrFinish = false;


                        GlobalVariable.IsReadyForCheck = true;

                        GlobalVariable.IsFirstTimeHomeFinish = true;
                        return true;
                    });
                }
            }
        }
        private bool checkProductStatus(out int status)
        {
            status = 0;

            return true;
        }
        private bool checkAllAxisInLastPosition(out string errInfo)
        {
            errInfo = "";
            foreach (var item in MachineResource.Instance.MachineAxis.Values)
            {
                if (Math.Abs(item.Position - item.LastPosition) > 0.1)
                {
                    errInfo = $"轴[{item.Description}]不在系统自动运行暂停时的位置:[{item.LastPosition}],请恢复!";
                    return false;
                }
            }
            return true;
        }
        public void ModuleWarn(string moduleName)
        {
            GlobalVariable.ColorLight?.Warn();
            moduleList2.AddWarnModule(moduleName);
        }
        public void ModuleReset(string moduleName)
        {
            GlobalVariable.ColorLight?.Pause();
            moduleList2.RemoveWarnModule(moduleName);
            if (this.IsHandleCreated)
            {
                this.BeginInvoke(new Action(() =>
                {
                    l_WarnMethod.Text = "无报警";
                    l_WarnMethod.ForeColor = Color.Black;
                    l_WarnMethod.BackgroundStyle.BackColor = Color.AliceBlue;
                }));
            }
        }
        public void AllModuleReset()
        {
            moduleList2.RemoveWarnModule();
        }
        private void l_AlarmClear_Click(object sender, EventArgs e)
        {
            //清除报警状态
            GlobalVariable.IsSystemErr = false;
            GlobalVariable.ColorLight.Pause();
            this.l_WarnMethod.Text = "无报警";
            this.l_WarnMethod.BackgroundStyle.BackColor = Color.AliceBlue;
            this.l_WarnMethod.ForeColor = Color.Black;
            GlobalVariable.isSafeDoorOpen = false;
        }
        public void PauseClickUI()
        {
            if (GlobalVariable.IsSystemHoming)
            {
                this.btn_Home.Enabled = true;
                this.btn_Stop.Enabled = true;
            }
            else
            {
                this.btn_Start.Enabled = true;
                this.btn_Stop.Enabled = true;
            }
        }
        public void UpdateUPH(string val)
        {
            aT_Info.Nodes[0].Cells[2].Text = $"{val} pcs";
        }
        public void UpdateCT(string item, string val)
        {
            if (item == "FrontCT")
            {
                aT_Info.Nodes[7].Cells[2].Text = $"{val} s";
            }
            else if (item == "BackCT")
            {
                aT_Info.Nodes[8].Cells[2].Text = $"{val} s";
            }
            else if (item == "UPH")
            {
                aT_Info.Nodes[0].Cells[2].Text = $"{val} pcs";
            }
            else if (item.Equals("机械手CT"))
            {
                aT_Info.Nodes[0].Nodes[0].Cells[2].Text = $"{val} s";
            }
            else if (item.Equals("中转站CT"))
            {
                aT_Info.Nodes[0].Nodes[1].Cells[2].Text = $"{val} s";
            }
            else if (item.Equals("前左ArmCT"))
            {
                aT_Info.Nodes[0].Nodes[2].Cells[2].Text = $"{val} s";
            }
            else if (item.Equals("前右ArmCT"))
            {
                aT_Info.Nodes[0].Nodes[3].Cells[2].Text = $"{val} s";
            }
            else if (item.Equals("后左ArmCT"))
            {
                aT_Info.Nodes[0].Nodes[4].Cells[2].Text = $"{val} s";
            }
            else if (item.Equals("后右CT"))
            {
                aT_Info.Nodes[0].Nodes[5].Cells[2].Text = $"{val} s";
            }
            else if (item.Equals("机械手2CT"))
            {
                aT_Info.Nodes[0].Nodes[6].Cells[2].Text = $"{val} s";
            }
            else if (item.Equals("中转站2CT"))
            {
                aT_Info.Nodes[0].Nodes[7].Cells[2].Text = $"{val} s";
            }
            else
            {
                CTModel mode;
                if (Enum.TryParse(item.ToString(), out mode))
                {
                    aT_Info.Nodes[0].Nodes[8 + ((int)mode)].Cells[2].Text = $"{val} s";
                }
            }
        }
        public void UpdateCount(string item, string val)
        {
            if (item == "Input")
            {
                aT_Info.Nodes[1].Cells[2].Text = $"{val} pcs";
            }
            else if (item == "NG")
            {
                aT_Info.Nodes[2].Cells[2].Text = $"{val} pcs";
            }
            else if (item == "OK")
            {
                aT_Info.Nodes[3].Cells[2].Text = $"{val} pcs";
            }
            else if (item == "ScanNG")
            {
                aT_Info.Nodes[4].Cells[2].Text = $"{val} pcs";
            }
            else if (item == "DownTime")
            {
                aT_Info.Nodes[5].Cells[2].Text = $"{val} s";
            }
            else if (item == "Output")
            {
                aT_Info.Nodes[6].Cells[2].Text = $"{val} pcs";
            }
            else if (item == "MesNG")
            {
                aT_Info.Nodes[9].Cells[2].Text = $"{val} pcs";
            }
        }
        List<string> warnNameList;
        public void UpdateWarnStatics()
        {
            //Dictionary<string, int> alarms = new Dictionary<string, int>();
            //alarms.Add("报警xxxxxxxxxxxxx1", 6);
            //alarms.Add("报警xxxxxxxxxxxxxxxxxxxxxxxxx2", 5);
            //alarms.Add("报警xxxxxxxx3", 4);
            //alarms.Add("报警xxxxxx4", 4);
            //alarms.Add("报警xxxxxxxxx5", 3);
            //alarms.Add("报警xxxxxxxxxx6", 1);
            //alarms.Add("报警xxxxxxxx7", 1);
            //alarms.Add("报警xxxxx8", 1);
            //alarms.Add("报警x9", 1);
            //alarms.Add("报警xxxxxxxxxx10", 1);
            Dictionary<string, int> descSortByValue = DescSortByValue(GlobalVariable.AlarmDict);
            warnNameList = descSortByValue.Keys.ToList();
            List<AlarmDistribution> alarmDistributions = new List<AlarmDistribution>();
            int index = 0;
            foreach (KeyValuePair<string, int> kvp in descSortByValue)
            {
                alarmDistributions.Add(new AlarmDistribution() { AlarmName = $"报警{index + 1}", AlarmNum = kvp.Value });
                index++;
            }
            this.BeginInvoke(new Action(() =>
            {
                this.chart2.BeginInvoke(new ChartDelegateAlarmDistribution(ChartAlarmDistributionMethod), this.chart2, alarmDistributions);
            }));
        }
        public static Dictionary<K, V> DescSortByValue<K, V>(Dictionary<K, V> dictionary)
        {
            var result = from obj in dictionary orderby obj.Value descending select obj;
            Dictionary<K, V> descSortByValue = new Dictionary<K, V>();
            foreach (var item in result)
            {
                descSortByValue.Add(item.Key, item.Value);
            }
            return descSortByValue;
        }
        public static void ChartAlarmDistributionMethod(Chart _Chart, List<AlarmDistribution> list)
        {
            //清空chart图表
            _Chart.Series["Series1"].Points.Clear();

            // 设置圆柱宽度
            _Chart.Series["Series1"]["PointWidth"] = "0.6";

            List<Color> colorList = new List<Color>();
            colorList.Add(Color.FromArgb(255, 192, 192));
            colorList.Add(Color.FromArgb(255, 224, 192));
            colorList.Add(Color.FromArgb(255, 255, 192));
            colorList.Add(Color.FromArgb(192, 255, 192));
            colorList.Add(Color.FromArgb(192, 255, 255));
            colorList.Add(Color.FromArgb(192, 192, 255));
            colorList.Add(Color.FromArgb(255, 192, 255));
            colorList.Add(Color.FromArgb(255, 192, 192));
            colorList.Add(Color.FromArgb(255, 224, 192));
            colorList.Add(Color.FromArgb(255, 255, 192));
            colorList.Add(Color.FromArgb(192, 255, 192));
            colorList.Add(Color.FromArgb(192, 255, 255));
            colorList.Add(Color.FromArgb(192, 192, 255));
            colorList.Add(Color.FromArgb(255, 192, 255));
            //
            for (int i = 0; i < list.Count; i++)
            {
                if (i > 9)
                    continue;
                _Chart.Series["Series1"].Points.AddXY(list[i].AlarmName, list[i].AlarmNum);
                _Chart.Series["Series1"].Points[i].Label = list[i].AlarmNum + "次";
                _Chart.Series["Series1"].Points[i].Color = colorList[i];
            }
            if (list == null || list.Count == 0)
                return;
            _Chart.ChartAreas[0].AxisY.Maximum = list[0].AlarmNum;
        }
        public void SetPie(StationTestResult testResult, Nexus.Windows.Forms.PieChart chart)
        {
            if (chart.Items.Count > 0)
            {
                if (testResult.TotalTestCount == 0)
                {
                    (chart.Items[0] as PieChartItem).Weight = 100;
                    for (int i = 1; i < chart.Items.Count; i++)
                    {
                        (chart.Items[i] as PieChartItem).Weight = 0;
                    }
                    return;
                }
                int totalNGCount = 0;
                foreach (var item in testResult.NGCounts.Values)
                {
                    totalNGCount += item;
                }
                (chart.Items[0] as PieChartItem).Weight = (testResult.TotalTestCount - totalNGCount) * 100.0 / testResult.TotalTestCount;
                (chart.Items[0] as PieChartItem).ToolTipText = $"OK: {(chart.Items[0] as PieChartItem).Weight.ToString("0.0")}%";
                for (int i = 1; i < chart.Items.Count; i++)
                {
                    (chart.Items[i] as PieChartItem).Weight = (testResult.NGCounts[i] * 100.0) / testResult.TotalTestCount;
                    (chart.Items[i] as PieChartItem).ToolTipText = $"NG{i}: {((testResult.NGCounts[i] * 100.0) / testResult.TotalTestCount).ToString("0.0")}%";
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, "Test Message", "Main", 0, "系统"));
        }

        private void btn_ClearFilter_Click(object sender, EventArgs e)
        {
            GridPanel panel = sGC_Log.PrimaryGrid;
            foreach (GridColumn column in panel.Columns)
                column.FilterExpr = null;
        }

        bool _isShowFilter = false;
        FormRobotDebug robotDebugForm = null;
        private void btn_ShowFilter_Click(object sender, EventArgs e)
        {
            //MachineResource.Instance.MachineAxis["下料仓Y轴"].Zero();
            _isShowFilter = !_isShowFilter;
            this.sGC_Log.PrimaryGrid.Filter.Visible = _isShowFilter;


            if (robotDebugForm == null || robotDebugForm.IsDisposed)
            {
                robotDebugForm = new FormRobotDebug();
                robotDebugForm.StartPosition = FormStartPosition.CenterScreen;
                robotDebugForm.Show();
            }
            else
            {
                if (robotDebugForm.WindowState == FormWindowState.Minimized)
                    robotDebugForm.WindowState = FormWindowState.Normal;
                robotDebugForm.BringToFront();
            }
        }
        bool isShow = false;
        private void tooltipDisplayDelay_Tick(object sender, EventArgs e)
        {
            tooltipDisplayDelay.Stop();
            ShowNodeTooltip(_currentButton);
        }
        private void ShowNodeTooltip(LabelX button)
        {
            NodeSuperTooltipProvider sp = button.Tag as NodeSuperTooltipProvider;
            sp.Show();
        }
        private void HideNodeTooltip(LabelX button)
        {
            NodeSuperTooltipProvider sp = button.Tag as NodeSuperTooltipProvider;
            sp.Hide();
        }
        private void btn_Start_MouseEnter(object sender, EventArgs e)
        {
        }

        private void btn_Start_MouseLeave(object sender, EventArgs e)
        {
        }

        private void l_WarnMethod_MouseEnter(object sender, EventArgs e)
        {
        }

        private void l_WarnMethod_MouseLeave(object sender, EventArgs e)
        {
        }
        LabelX _currentButton = null;
        private void Warn_MouseEnter(object sender, EventArgs e)
        {
            _currentButton = sender as LabelX;
            tooltipDisplayDelay.Stop();
            ShowNodeTooltip(_currentButton);
        }
        private void Warn_MouseLeave(object sender, EventArgs e)
        {
            _currentButton = sender as LabelX;
            HideNodeTooltip(_currentButton);
            tooltipDisplayDelay.Stop();
        }

        private void l_WarnContent_MouseEnter(object sender, EventArgs e)
        {

        }
        public void UserChanged()
        {
            if (GlobalVariable.UserRole.UserLevel == 2)
            {
                this.sT_Position.Visible = true;
                this.sT_Tester.Visible = true;
                this.sT_Logic.Visible = true;
                //this.btn_RobotStop.Visible = true;
                //this.btn_RobotReset.Visible = true;
                //this.btn_RobotPause.Visible = true;
                //this.btn_RobotContinue.Visible = true;
                //this.btn_RobotStart.Visible = true;
                this.aT_Info.ContextMenuStrip = cMS_Clear;
                //this.btn_Eco.Visible = false;
            }
            else if (GlobalVariable.UserRole.UserLevel == 0)
            {
                this.sT_Position.Visible = false;
                this.sT_Tester.Visible = false;
                this.sT_Logic.Visible = false;
                //this.btn_RobotStop.Visible = false;
                //this.btn_RobotReset.Visible = false;
                //this.btn_RobotPause.Visible = false;
                //this.btn_RobotContinue.Visible = false;
                //this.btn_RobotStart.Visible = false;
                this.aT_Info.ContextMenuStrip = null;
                //this.btn_Eco.Visible = false;
            }
            else if (GlobalVariable.UserRole.UserLevel == 1)
            {
                this.sT_Position.Visible = false;
                this.sT_Tester.Visible = false;
                this.sT_Logic.Visible = false;
                //this.btn_RobotStop.Visible = false;
                //this.btn_RobotReset.Visible = true;
                //this.btn_RobotPause.Visible = false;
                //this.btn_RobotContinue.Visible = false;
                //this.btn_RobotStart.Visible = false;
                this.aT_Info.ContextMenuStrip = null;
                //this.btn_Eco.Visible = false;
            }
            moduleList2.IsInEditUserRole = GlobalVariable.UserRole.UserLevel > 0;
        }
        int timecount = 0;
        int timecount2 = 0;
        private void t_Robot_Tick(object sender, EventArgs e)
        {
            this.textBoxX1.Text = MachineMessageScheduler.Instance.MessageCount.ToString();
            timecount++;
            if (timecount == 10)
            {
                if (GlobalVariable.IsClearLater || GlobalVariable.IsClearNow)
                {
                    //this.l_Clear.BackgroundStyle.BorderWidth = this.l_Clear.BackgroundStyle.BorderWidth == 0 ? 2 : 0;
                    this.l_Clear.BackgroundStyle.BackColor = this.l_Clear.BackgroundStyle.BackColor == Color.DeepSkyBlue ? Color.LightGray : Color.DeepSkyBlue;
                    this.l_Clear.Refresh();
                }
                timecount = 0;
            }
            if (timecount >= 100000)
                timecount = 0;

            timecount2++;
            if (timecount2 == 10)
            {
                if (GlobalVariable.IsSpotChecking)
                {
                    //this.l_Clear.BackgroundStyle.BorderWidth = this.l_Clear.BackgroundStyle.BorderWidth == 0 ? 2 : 0;
                    this.l_SpotCheck.BackgroundStyle.BackColor = this.l_SpotCheck.BackgroundStyle.BackColor == Color.LightGreen ? Color.LightGray : Color.LightGreen;
                    this.l_SpotCheck.Refresh();
                }
                timecount2 = 0;
            }
            if (timecount2 >= 100000)
                timecount2 = 0;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            //GlobalVariable.RobotControlStatus[1] = true;
        }

        private void btn_RobotStop_Click(object sender, EventArgs e)
        {
            //GlobalVariable.RobotControlStatus[1] = !GlobalVariable.RobotControlStatus[1];
        }

        private void btn_RobotReset_Click(object sender, EventArgs e)
        {
            //GlobalVariable.RobotControlStatus[4] = !GlobalVariable.RobotControlStatus[4];
        }
        private void btn_RobotPause_Click(object sender, EventArgs e)
        {
            GlobalVariable.IsEcoMode = !GlobalVariable.IsEcoMode;
            if (GlobalVariable.IsEcoMode)
            {
                Thread.Sleep(500);
                MachineResource.Instance.MachineCylinder["红灯"].Off();
                MachineResource.Instance.MachineCylinder["绿灯"].Off();
                MachineResource.Instance.MachineCylinder["黄灯"].Off();
                MachineResource.Instance.MachineCylinder["蜂鸣器"].Off();
                MachineResource.Instance.MachineCylinder["启动灯"].Off();
                MachineResource.Instance.MachineCylinder["复位灯"].Off();
                MachineResource.Instance.MachineCylinder["停止灯"].Off();
            }
        }

        private void btn_RobotStart_Click(object sender, EventArgs e)
        {
            MonitorHelper.CloseMonitor();
            if (MachineResource.Instance.MachineTcpClient.ContainsKey("一键熄屏1"))
            {
                TCPClient client = MachineResource.Instance.MachineTcpClient["一键熄屏1"];
                if (!client.IsConnected)
                    client.Connect();
                client.Send("CloseMonitor\r\n");
            }
            if (MachineResource.Instance.MachineTcpClient.ContainsKey("一键熄屏2"))
            {
                TCPClient client = MachineResource.Instance.MachineTcpClient["一键熄屏2"];
                if (!client.IsConnected)
                    client.Connect();
                client.Send("CloseMonitor\r\n");
            }
        }

        private void btn_RobotContinue_Click(object sender, EventArgs e)
        {
            if (MachineResource.Instance.MachineCylinder["日光灯"].AlreadyOn())
                MachineResource.Instance.MachineCylinder["日光灯"].Off();
            else
                MachineResource.Instance.MachineCylinder["日光灯"].On();
        }
        bool stopUpdateLastPosition = false;
        bool isFirst = false;
        private void t_Holder_Tick(object sender, EventArgs e)
        {
            if (!stopUpdateLastPosition)
            {
                foreach (var item in MachineResource.Instance.MachineAxis.Values)
                {
                    foreach (GridRow row in sGC_AxisPausePosition.PrimaryGrid.Rows)
                    {
                        if (row.Cells[0].Value.ToString().Equals(item.Description))
                        {
                            row.Cells[1].Value = item.LastPosition;
                        }
                    }
                }
            }
        }

        private void btn_OUT_Click(object sender, EventArgs e)
        {
            int index = Convert.ToInt32((sender as ButtonX).Name.Substring(7));
            GlobalVariable.PCWritePLCData[index - 1] = !GlobalVariable.PCWritePLCData[index - 1];
        }

        private void button1_Click_2(object sender, EventArgs e)
        {
        }

        private void l_Clear_Click(object sender, EventArgs e)
        {
            if (GlobalVariable.IsClearLater || GlobalVariable.IsClearNow)
            {
                MessageBox.Show("系统已在清料模式中,请等待清料完成...", "清料", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            MessageBoxResult result = MyMessageBoxEx.ShowBox("确定进入清料模式吗?\r\n点击 立即 立即开始清料\r\n点击 做完 做完当前Tray盘后开始清料", "清料", new List<string>() { "立即", "做完", "取消" }, MessageBoxType.Info);
            if (result == MessageBoxResult.First)
            {
                GlobalVariable.IsClearNow = true;
                GlobalVariable.IsClearNow2 = true;
            }
            else if (result == MessageBoxResult.Second)
            {
                GlobalVariable.IsClearLater = true;
                GlobalVariable.IsClearLater2 = true;
            }
            else if (result == MessageBoxResult.Cancel)
                return;
            timecount = 0;
        }

        private void button1_Click_3(object sender, EventArgs e)
        {
        }

        private void 清空数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            aT_Info.Nodes[1].Cells[2].Text = $"0 pcs";
            aT_Info.Nodes[2].Cells[2].Text = $"0 pcs";
            aT_Info.Nodes[3].Cells[2].Text = $"0 pcs";
            aT_Info.Nodes[4].Cells[2].Text = $"0 pcs";
            aT_Info.Nodes[5].Cells[2].Text = $"0 s";
            aT_Info.Nodes[6].Cells[2].Text = $"0 pcs";
            aT_Info.Nodes[7].Cells[2].Text = $"0 s";
            aT_Info.Nodes[8].Cells[2].Text = $"0 s";
            aT_Info.Nodes[9].Cells[2].Text = $"0 s";

            lock (GlobalVariable.TesterOKDataLock)
            {
                GlobalVariable.CurrentMachineData.TotalOKCount = 0;
            }
            lock (GlobalVariable.TesterNGDataLock)
            {
                GlobalVariable.CurrentMachineData.TotalNGCount = 0;
            }
            lock (GlobalVariable.UPHLock)
            {
                GlobalVariable.UPHListBack.Clear();
                GlobalVariable.UPHListFront.Clear();
            }
            GlobalVariable.CurrentMachineData.TotalOutputCount = 0;
            GlobalVariable.CurrentMachineData.TotalInputCount = 0;
            GlobalVariable.CurrentMachineData.TotalScanNGCount = 0;
            GlobalVariable.CurrentMachineData.TotalMesNGCount = 0;
            GlobalVariable.CurrentMachineData.DownTimes = 0;
            GlobalVariable.SaveMachineData(GlobalVariable.CurrentMachineData);
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定删除所有测试数据吗?", "测试数据", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
            {
                GlobalVariable.StationResults = new List<StationTestResult>();
                for (int i = 0; i < 4; i++)
                {
                    StationTestResult st = new StationTestResult();
                    st.TotalTestCount = 0;
                    st.NGCounts = new SerializableDictionary<int, int>();
                    st.NGCounts.Add(1, 0);
                    st.NGCounts.Add(2, 0);
                    st.NGCounts.Add(3, 0);
                    st.NGCounts.Add(4, 0);
                    GlobalVariable.StationResults.Add(st);
                }

                XmlSerializerHelper<List<StationTestResult>>.SerializeToFile(GlobalVariable.StationResults, PathHelper.GetConfigPath("Machine") + "TestData.xml");
            }
        }

        private void sGC_AxisPausePosition_CellValueChanged(object sender, GridCellValueChangedEventArgs e)
        {
            //修改暂停位置
            if (e.GridCell.ColumnIndex == 1)
            {


            }
        }

        private void l_Update_Click(object sender, EventArgs e)
        {
            stopUpdateLastPosition = true;
            sGC_AxisPausePosition.Enabled = true;
        }

        private void l_Confirm_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show($"确定修改轴暂停位置吗?", "修改位置", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                foreach (GridRow row in sGC_AxisPausePosition.PrimaryGrid.Rows)
                {
                    string axisName = row.Cells[0].Value.ToString();
                    double newPosition = Convert.ToDouble(row.Cells[1].Value);
                    MachineResource.Instance.MachineAxis[axisName].LastPosition = newPosition;
                    stopUpdateLastPosition = false;
                    sGC_AxisPausePosition.Enabled = false;
                }
            }
        }

        private void button1_Click_4(object sender, EventArgs e)
        {
        }

        private void l_CancelBeep_Click(object sender, EventArgs e)
        {
            GlobalVariable.ColorLight.BeepOff();
        }

        private void l_CancelBeep_MouseDown(object sender, MouseEventArgs e)
        {
            l_CancelBeep.BackgroundStyle.BackColor = Color.WhiteSmoke;
        }

        private void l_CancelBeep_MouseUp(object sender, MouseEventArgs e)
        {
            l_CancelBeep.BackgroundStyle.BackColor = Color.FromArgb(224, 172, 94);
        }

        private void chart2_MouseClick(object sender, MouseEventArgs e)
        {
            //HitTestResult mytestresult = new HitTestResult();//它表示命中测试的返回值
            //mytestresult = chart2.HitTest(e.X, e.Y);//获取我们Chart控件的折线图在这个坐标的值
            //if (e.Button == MouseButtons.Left)//判断是否是鼠标左键点击
            //{
            //    if (mytestresult.ChartElementType == ChartElementType.DataPoint)//判断我们点击这个返回集是否是chart的数据点的类型
            //    {
            //        toolTip1.AutoPopDelay = 5000;//表示tooltip在这个控件中保留展示的时间
            //        toolTip1.InitialDelay = 1000;//表示鼠标指针必须在这里静止的时间
            //        toolTip1.ReshowDelay = 500;//可以缩短或延长在显示上一个工具提示窗口后显示工具提示窗口之前等待的时间tooltip
            //        toolTip1.ShowAlways = true;//获取或设置一个值，该值指示是否显示工具提示窗口，甚至是在其父控件不活动的时候。

            //        try
            //        {
            //            int index = Convert.ToInt32(chart2.Series[0].Points[mytestresult.PointIndex].AxisLabel.Substring(2));
            //            toolTip1.SetToolTip(chart2, warnNameList[index - 1]);//设置ToolTip展示的值的内容，mytestresult.Series.Name表示折线的名字，chart1.Series[0].Points[mytestresult.PointIndex]表示chart图表中的第0（从0开始也就是第一条）条折线的数据点的第多少个，
            //                                                                 //也可以设置chart1.Series[0].Points[mytestresult.PointIndex].XValue;这个代表你点击这个点的x轴的值，chart1.Series[0].Points[mytestresult.PointIndex].YValues[0];这个代表你点击的点Y轴的值

            //        }
            //        catch (Exception)
            //        {

            //        }
            //    }
            //}
        }

        private void chart2_MouseMove(object sender, MouseEventArgs e)
        {
            HitTestResult mytestresult = new HitTestResult();//它表示命中测试的返回值
            mytestresult = chart2.HitTest(e.X, e.Y);//获取我们Chart控件的折线图在这个坐标的值
            //if (e.Button == MouseButtons.Left)//判断是否是鼠标左键点击
            {
                if (mytestresult.ChartElementType == ChartElementType.DataPoint)//判断我们点击这个返回集是否是chart的数据点的类型
                {
                    toolTip1.AutoPopDelay = 5000;//表示tooltip在这个控件中保留展示的时间
                    toolTip1.InitialDelay = 1000;//表示鼠标指针必须在这里静止的时间
                    toolTip1.ReshowDelay = 500;//可以缩短或延长在显示上一个工具提示窗口后显示工具提示窗口之前等待的时间tooltip
                    toolTip1.ShowAlways = true;//获取或设置一个值，该值指示是否显示工具提示窗口，甚至是在其父控件不活动的时候。

                    try
                    {
                        int index = Convert.ToInt32(chart2.Series[0].Points[mytestresult.PointIndex].AxisLabel.Substring(2));
                        toolTip1.SetToolTip(chart2, warnNameList[index - 1]);//设置ToolTip展示的值的内容，mytestresult.Series.Name表示折线的名字，chart1.Series[0].Points[mytestresult.PointIndex]表示chart图表中的第0（从0开始也就是第一条）条折线的数据点的第多少个，
                                                                             //也可以设置chart1.Series[0].Points[mytestresult.PointIndex].XValue;这个代表你点击这个点的x轴的值，chart1.Series[0].Points[mytestresult.PointIndex].YValues[0];这个代表你点击的点Y轴的值

                    }
                    catch (Exception)
                    {

                    }
                }
            }
        }
        private void t_ControlButton_Tick(object sender, EventArgs e)
        {
            if (true)
            {
                if (MachineResource.Instance.MachineSensor.ContainsKey("启动按钮") &&
                    MachineResource.Instance.MachineSensor["启动按钮"].WaitOn())
                {
                    Thread.Sleep(50);
                    if (MachineResource.Instance.MachineSensor["启动按钮"].WaitOn())
                    {
                        btn_Start.PerformClick();
                    }
                }
                if (MachineResource.Instance.MachineSensor.ContainsKey("暂停按钮") &&
                    MachineResource.Instance.MachineSensor["暂停按钮"].WaitOn())
                {
                    Thread.Sleep(50);
                    if (MachineResource.Instance.MachineSensor["暂停按钮"].WaitOn())
                    {
                        btn_Pause.PerformClick();
                    }
                }
                if (MachineResource.Instance.MachineSensor.ContainsKey("停止按钮") && MachineResource.Instance.MachineSensor["停止按钮"].WaitOn())
                {
                    Thread.Sleep(50);
                    //if (MachineResource.Instance.MachineSensor["停止按钮"].WaitOn())
                    //{
                    //    btn_Stop.PerformClick();
                    //}
                    if (MachineResource.Instance.MachineSensor["停止按钮"].WaitOn())
                    {
                        btn_Pause.PerformClick();
                    }
                }
                if (MachineResource.Instance.MachineSensor.ContainsKey("复位按钮") && MachineResource.Instance.MachineSensor["复位按钮"].WaitOn())
                {
                    //复位按钮按下
                    System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                    sw.Start();
                    //持续了3s
                    while (MachineResource.Instance.MachineSensor["复位按钮"].WaitOn() && sw.ElapsedMilliseconds < 2000)
                    {
                        Thread.Sleep(20);
                    }
                    sw.Stop();
                    if (!MachineResource.Instance.MachineSensor["复位按钮"].WaitOn() && sw.ElapsedMilliseconds >= 50)
                    {
                        l_AlarmClear_Click(this, null);
                    }
                    if (sw.ElapsedMilliseconds >= 2000)
                    {
                        btn_Home.PerformClick();
                    }
                }
            }
        }

        bool ngTrayExist = false;
        bool startChangeNGTray = false;
        bool isHasBarcodeNGTray = false;
        bool isHasBarcodeNGTrayInPosition = false;
        private void t_Tray_Tick(object sender, EventArgs e)
        {
            if (GlobalVariable.IsSimulate)
            {
                dB_FeedTray1.Repaint();
                dB_OKTray1Boat1.Repaint();
                dB_OKTray1Boat2.Repaint();
                dB_FeedTray2.Repaint();
                dB_OKTray2Boat1.Repaint();
                dB_OKTray2Boat2.Repaint();

                dB_RobotHeaderFront.Repaint();
                dB_RobotHeaderBack.Repaint();

                dB_BufferTrayFront2.Repaint();
                dB_BufferTrayFront1.Repaint();
                dB_ScanNGTrayFront1.Repaint();
                dB_ANGTrayFront1.Repaint();
                dB_ABNGTrayFront1.Repaint();
                dB_ABBNGTrayFront1.Repaint();
                dB_SpotCheck1.Repaint();

                dB_BufferTrayBack2.Repaint();
                dB_BufferTrayBack1.Repaint();
                dB_ScanNGTrayBack1.Repaint();
                dB_ANGTrayBack1.Repaint();
                dB_ABNGTrayBack1.Repaint();
                dB_ABBNGTrayBack1.Repaint();
                dB_SpotCheck2.Repaint();

                dB_PrecisionRecycleTrayFrontUp1.Repaint();
                dB_PrecisionRecycleTrayFrontUp2.Repaint();
                dB_PrecisionFeedTrayFrontUp1.Repaint();
                dB_PrecisionFeedTrayFrontUp2.Repaint();

                dB_PrecisionRecycleTrayFrontDown1.Repaint();
                dB_PrecisionRecycleTrayFrontDown2.Repaint();
                dB_PrecisionFeedTrayFrontDown1.Repaint();
                dB_PrecisionFeedTrayFrontDown2.Repaint();

                dB_PrecisionRecycleTrayBackUp1.Repaint();
                dB_PrecisionRecycleTrayBackUp2.Repaint();
                dB_PrecisionFeedTrayBackUp1.Repaint();
                dB_PrecisionFeedTrayBackUp2.Repaint();

                dB_PrecisionRecycleTrayBackDown1.Repaint();
                dB_PrecisionRecycleTrayBackDown2.Repaint();
                dB_PrecisionFeedTrayBackDown1.Repaint();
                dB_PrecisionFeedTrayBackDown2.Repaint();

                dB_Arm1Feed.Repaint();
                dB_Arm1Recycle.Repaint();
                dB_Arm2Feed.Repaint();
                dB_Arm2Recycle.Repaint();
                dB_Arm3Feed.Repaint();
                dB_Arm3Recycle.Repaint();
                dB_Arm4Feed.Repaint();
                dB_Arm4Recycle.Repaint();

                dB_TesterTrayFrontLeftA.Repaint();
                dB_TesterTrayFrontLeftB.Repaint();
                dB_TesterTrayFrontLeftC.Repaint();

                dB_TesterTrayFrontRightA.Repaint();
                dB_TesterTrayFrontRightB.Repaint();
                dB_TesterTrayFrontRightC.Repaint();

                dB_TesterTrayBacktLeftA.Repaint();
                dB_TesterTrayBacktLeftB.Repaint();
                dB_TesterTrayBacktLeftC.Repaint();

                dB_TesterTrayBackRightA.Repaint();
                dB_TesterTrayBackRightB.Repaint();
                dB_TesterTrayBackRightC.Repaint();
            }

            for (int i = 0; i < 12; i++)
            {
                if (SystemConfig.Instance.UsingStatus.TesterInUseStatus[i])
                {
                    testerEnableStatusLabels[i].BackColor = Color.LimeGreen;
                    testerEnableStatusLabels[i].ForeColor = Color.White;
                    testerEnableStatusLabels[i].Text = "启用";
                }
                else
                {
                    testerEnableStatusLabels[i].BackColor = Color.DarkGray;
                    testerEnableStatusLabels[i].ForeColor = Color.Black;
                    testerEnableStatusLabels[i].Text = "禁用";
                }
            }

            lock (GlobalVariable.SNLock)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("SN");
                dt.Columns.Add("Tester1");
                dt.Columns.Add("Tester2");
                dt.Columns.Add("Tester3");
                foreach (var item in GlobalVariable.SN2TestCount)
                {
                    dt.Rows.Add(item.Key, item.Value[0], item.Value[1], item.Value[2]);
                }
                dGV_GrrData.DataSource = dt;
            }
        }

        private void labelX19_Click(object sender, EventArgs e)
        {
            if (_grrForm == null || _grrForm.IsDisposed)
            {
                _grrForm = new FormGRR();
                _grrForm.StartPosition = FormStartPosition.CenterScreen;
                _grrForm.Show();
            }
            else
            {
                if (_grrForm.WindowState == FormWindowState.Minimized)
                    _grrForm.WindowState = FormWindowState.Normal;
                _grrForm.BringToFront();
            }
        }

        private void labelX1_Click(object sender, EventArgs e)
        {
            SystemConfig.Instance.GetProductVacDelay = Convert.ToInt32(nUD_Time1.Value);
            SystemConfig.Instance.Save();
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            if (File.Exists(PathHelper.GetConfigPath("Machine") + "Alarm.xml"))
            {
                File.Delete(PathHelper.GetConfigPath("Machine") + "Alarm.xml");
                GlobalVariable.AlarmDict = new SerializableDictionary<string, int>();
                UpdateWarnStatics();
            }
        }

        private void button1_Click_5(object sender, EventArgs e)
        {
            MachineResource.Instance.MachineTcpClient["测试站右1"].Send($"StartTest,VSN11111", out string recvStr, 5000);

            while (!MachineResource.Instance.MachineTcpClient["测试站右1"].ReceivedStringQueue.TryDequeue(out string recvStr1))
            {
                Thread.Sleep(20);
            }

            MachineResource.Instance.MachineTcpClient["测试站结果右1"].Send($"GetResult,VSN11111", out string recvStr2, 5000);

            while (!MachineResource.Instance.MachineTcpClient["测试站结果右1"].ReceivedStringQueue.TryDequeue(out string recvStr3))
            {
                Thread.Sleep(20);
            }

        }

        private async void labelX12_Click(object sender, EventArgs e)
        {
        }

        private async void labelX2_Click(object sender, EventArgs e)
        {
        }

        private void labelX20_Click(object sender, EventArgs e)
        {

        }

        private void p_Robot_Click(object sender, EventArgs e)
        {
        }
        bool changeColor = false;
        bool changeColor2 = true;
        private void timer1_Tick_1(object sender, EventArgs e)
        {
            lbl_BackSNBoat.Text = $"SN:{GlobalVariable.CurrentBackOKBoatSN}";
            lbl_FrontSNBoat.Text = $"SN:{GlobalVariable.CurrentFrontOKBoatSN}";
            if (SystemConfig.Instance.MesParam.EnableMES)
            {
                l_MES.BackColor = Color.LimeGreen;
                l_MES.Text = "MES启用";
                l_MES.ForeColor = Color.White;
            }
            else
            {
                l_MES.BackColor = changeColor ? Color.Red : Color.White;
                l_MES.ForeColor = changeColor ? Color.White : Color.Black;
                l_MES.Text = "MES禁用";
                changeColor = !changeColor;
            }

            if (GlobalVariable.IsOnlineRetest)
            {
                l_Retest.BackColor = Color.LimeGreen;
                l_Retest.Text = "复测启用";
                l_Retest.ForeColor = Color.White;
            }
            else
            {
                l_Retest.BackColor = changeColor2 ? Color.Red : Color.White;
                l_Retest.ForeColor = changeColor2 ? Color.White : Color.Black;
                l_Retest.Text = "复测禁用";
                changeColor2 = !changeColor2;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
        }

        private void rB_Module_CheckedChanged(object sender, EventArgs e)
        {
#if ALT
            if(rB_Module.Checked)
            {
                p_Layout.Visible = true;
                p_Tray.Visible = false;
            }
#else
            if (rB_Module.Checked)
            {
                p_Layout.Visible = true;
                p_Tray.Visible = false;
            }
#endif
        }

        private void rB_Status_CheckedChanged(object sender, EventArgs e)
        {
#if ALT
            if (rB_Status.Checked)
            {
                p_Layout.Visible = false;
                p_Tray.Visible = true;
            }
#else
            if (rB_Status.Checked)
            {
                p_Layout.Visible = false;
                p_Tray.Visible = true;
            }
#endif
        }

        private void button4_Click(object sender, EventArgs e)
        {
            GlobalVariable.NGButtonSimulatePress = true;
        }

        private void l_Conveyor_Click(object sender, EventArgs e)
        {
            if (_plcForm == null || _plcForm.IsDisposed)
            {
                _plcForm = new FormPLC();
                _plcForm.StartPosition = FormStartPosition.CenterScreen;
                _plcForm.Show();
            }
            else
            {
                if (_plcForm.WindowState == FormWindowState.Minimized)
                    _plcForm.WindowState = FormWindowState.Normal;
                _plcForm.BringToFront();
            }
        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            //ControlButton_Click(null,null);
            ;
        }

        private void l_AutoRetest_Click(object sender, EventArgs e)
        {

        }

        private void 清除数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定清除数据吗?", "清除数据", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                GlobalVariable.CurrentMachineData.TotalInputCount = 0;
                GlobalVariable.CurrentMachineData.TotalNGCount = 0;
                GlobalVariable.CurrentMachineData.TotalOKCount = 0;
                GlobalVariable.CurrentMachineData.TotalMesNGCount = 0;
                GlobalVariable.CurrentMachineData.TotalScanNGCount = 0;
                GlobalVariable.CurrentMachineData.DownTimes = 0;
                GlobalVariable.SaveMachineData(GlobalVariable.CurrentMachineData);

                UpdateCount("Input", "0");
                UpdateCount("NG", "0");
                UpdateCount("OK", "0");
                UpdateCount("ScanNG", "0");
                UpdateCount("DownTime", "0");
                UpdateCount("MesNG", "0");
            }
        }
        int lastTotalInput = GlobalVariable.CurrentMachineData.TotalInputCount;
        private void t_UPH_Tick(object sender, EventArgs e)
        {
            int currentTotalInput = GlobalVariable.CurrentMachineData.TotalInputCount;
            UpdateUPH(((currentTotalInput - lastTotalInput) * 12).ToString());
            lastTotalInput = currentTotalInput;
        }

        int moduleIndex;
        int testerIndex;
        private async void l_CheckStatus_Click(object sender, EventArgs e)
        {
            l_CheckStatus.Enabled = false;
            l_CheckStatus.Enabled = await Task.Run(() =>
            {
                bool bank1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndex}{testerIndex}") as TesterLogic).IsTesterEnabled(testerIndex - 1, 0);
                bool bank2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndex}{testerIndex}") as TesterLogic).IsTesterEnabled(testerIndex - 1, 1);

                this.BeginInvoke(new Action(() =>
                {
                    tB_Status.Text = $"Bank0:{bank1Status}, Bank1:{bank2Status}";
                }));
                return true;
            });
        }

        private void cB_Module_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cB_Module.SelectedIndex == -1)
                return;
            moduleIndex = cB_Module.SelectedIndex + 1;
        }

        private void cB_TesterNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cB_Module.SelectedIndex == -1)
            {
                MessageBox.Show("请先选择测试模组!");
                return;
            }
            if (cB_TesterNo.SelectedIndex == -1)
                return;
            testerIndex = (moduleIndex - 1) * 3 + cB_TesterNo.SelectedIndex + 1;
        }

        private async void l_StartTest_Click(object sender, EventArgs e)
        {
            l_StartTest.Enabled = false;
            rTB_Result.Text = "";
            l_StartTest.Enabled = await Task.Run(() =>
            {
                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndex}{testerIndex}") as TesterLogic);
                testerLogic.StartTest(testerIndex - 1, 0, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}", 0, out SendPackage sp1);
                testerLogic.StartTest(testerIndex - 1, 1, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-2", 0, out SendPackage sp2);
                testerLogic.WaitStartTest(testerIndex - 1, 0, sp1);
                testerLogic.WaitStartTest(testerIndex - 1, 1, sp2);
                DateTime startTime = DateTime.Now;
                TimeSpan ts = DateTime.Now - startTime;
                //手动测试时强制复位治具结果
                testerLogic.ResetResult();
                //手动测试时强制治具有料，否则收不到结果
                testerLogic.TesterTray.Helper.SetCellStatus(0, CellStatus.HasProduct);
                testerLogic.TesterTray.Helper.SetCellStatus(1, CellStatus.HasProduct);
                while (!testerLogic.AllEnabledTesterFinished() && ts.TotalMilliseconds < 60000)
                {
                    ts = DateTime.Now - startTime;
                    Thread.Sleep(10);
                }
                if (ts.TotalMilliseconds >= 60000)
                {
                    MessageBox.Show($"等待测试测试模组{testerIndex}测试完成超时!", "系统");
                    return true;
                }
                this.BeginInvoke(new Action(() =>
                {
                    rTB_Result.Text = $"测试结果:{testerLogic.GetResult()[0]},{testerLogic.GetResult()[1]}";
                }));
                return true;
            });
        }

        private void labelX7_Click(object sender, EventArgs e)
        {
            GlobalVariable.IsGrrMode = true;
            //menuMode.Image = Properties.Resources.GRR模式2;
            //GlobalVariable.MachineWorkMode = WorkMode.GRR;
            GlobalVariable.IsRobotDryRun = false;
            SystemConfig.Instance.TestParam.IsABBEnable = false;
            l_Mode.Text = "GRR";

            if (_grrForm == null || _grrForm.IsDisposed)
            {
                _grrForm = new FormGRR();
                _grrForm.StartPosition = FormStartPosition.CenterScreen;
                _grrForm.Show();
            }
            else
            {
                if (_grrForm.WindowState == FormWindowState.Minimized)
                    _grrForm.WindowState = FormWindowState.Normal;
                _grrForm.BringToFront();
            }

            GlobalVariable.SN2TestCount = new Dictionary<string, int[]>();
            GlobalVariable.SN2FinishStatus = new Dictionary<string, bool[]>();
        }

        private void l_Robot_Click(object sender, EventArgs e)
        {
            if (_testerForm == null || _testerForm.IsDisposed)
            {
                _testerForm = new FormTester();
                _testerForm.StartPosition = FormStartPosition.CenterScreen;
                _testerForm.Show();
            }
            else
            {
                if (_testerForm.WindowState == FormWindowState.Minimized)
                    _testerForm.WindowState = FormWindowState.Normal;
                _testerForm.BringToFront();
            }
        }

        private void l_Retest_Click(object sender, EventArgs e)
        {

        }

        private void l_MES_Click(object sender, EventArgs e)
        {

        }

        private async void l_CheckCylinder_Click(object sender, EventArgs e)
        {
            l_CheckCylinder.Enabled = false;
            l_CheckCylinder.Enabled = await Task.Run(() =>
            {
                bool ready1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndex}{testerIndex}") as TesterLogic).IsTesterReady(testerIndex - 1, 0);
                bool ready2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndex}{testerIndex}") as TesterLogic).IsTesterReady(testerIndex - 1, 1);

                this.BeginInvoke(new Action(() =>
                {
                    tB_Cylinder.Text = $"Ready0:{ready1Status}, Ready1:{ready2Status}";
                }));
                return true;
            });
        }

        private async void labelX7_Click_1(object sender, EventArgs e)
        {
            labelX7.Enabled = false;
            labelX7.Enabled = await Task.Run(() =>
            {
                bool loadStatus = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndex}{testerIndex}") as TesterLogic).OpenVac(testerIndex - 1, 0);
                bool loadStatus2 = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndex}{testerIndex}") as TesterLogic).OpenVac(testerIndex - 1, 1);

                if (!loadStatus)
                    MessageBox.Show("开真空失败");
                if (!loadStatus2)
                    MessageBox.Show("开真空失败");
                return true;
            });
        }

        private void panelEx10_Click(object sender, EventArgs e)
        {

        }

        private void label20_MouseDown(object sender, MouseEventArgs e)
        {
            this.l_AlarmReset.Image = Properties.Resources.复位64Gray;
        }

        private void label20_MouseUp(object sender, MouseEventArgs e)
        {
            this.l_AlarmReset.Image = Properties.Resources.复位64;
        }

        private void label20_Click(object sender, EventArgs e)
        {
            //清除报警状态
            GlobalVariable.IsSystemErr = false;
            GlobalVariable.ColorLight.Pause();
            this.l_WarnMethod.Text = "无报警";
            this.l_WarnMethod.BackgroundStyle.BackColor = Color.AliceBlue;
            this.l_WarnMethod.ForeColor = Color.Black;
            GlobalVariable.isSafeDoorOpen = false;
        }

        private void l_SpotCheck_Click(object sender, EventArgs e)
        {
            MessageBoxResult result = MyMessageBoxEx.ShowBox("确定进入 点检 模式吗?\r\n点击 确定 进入 点检 模式", "点检", new List<string>() { "确定", "取消" }, MessageBoxType.Info);
            if (result == MessageBoxResult.First)
            {
                GlobalVariable.IsGrrMode = false;
                GlobalVariable.IsCosmeticMode = false;
                GlobalVariable.IsSpotChecking = true;
            }
            else if (result == MessageBoxResult.Second)
            {
                return;
            }
            else if (result == MessageBoxResult.Cancel)
                return;
        }

        private async void Tester_Click(object sender, EventArgs e)
        {
            string sn1 = textBoxX2.Text;
            string sn2 = textBoxX3.Text;
            LabelX label = (LabelX)sender;
            string testerName = label.Text;
            int moduleIndexTemp = Convert.ToInt32(testerName.Substring(6, 1));
            int t = Convert.ToInt32(testerName.Substring(7, 1));
            int testerIndexTemp = moduleIndexTemp % 2 == 0 ? 3 + Convert.ToInt32(testerName.Substring(7, 1)) : Convert.ToInt32(testerName.Substring(7, 1));
            label.Text = $"Tester{moduleIndexTemp}{t}:-1,-1";
            label.BackgroundStyle.BackColor = Color.Coral;
            label.Enabled = false;
            label.Enabled = await Task.Run(() =>
            {
                bool bank1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterEnabled(testerIndexTemp - 1, 0);
                bool bank2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterEnabled(testerIndexTemp - 1, 1);

                if (bank1Status && bank2Status)
                {
                    bool ready1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 0);
                    bool ready2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 1);

                    if (!ready1Status || !ready2Status)
                    {
                        MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                    }
                    else
                    {
                        bool loadStatus = false;
                        bool loadStatus2 = false;
                        (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVacNoWait(testerIndexTemp - 1, 0, true);
                        (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVacNoWait(testerIndexTemp - 1, 1, true);
                        while (!(FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).WaitVacOpen(testerIndexTemp - 1, 0))
                        {
                            Thread.Sleep(20);
                        }
                        //if (!loadStatus || !loadStatus2)
                        //{
                        //    MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                        //}
                        //else
                        {
                            TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                            testerLogic.StartTest(testerIndexTemp - 1, 0, sn1, 0, out SendPackage sp1);
                            testerLogic.StartTest(testerIndexTemp - 1, 1, sn2, 0, out SendPackage sp2);
                            testerLogic.WaitStartTest(testerIndexTemp - 1, 0, sp1);
                            testerLogic.WaitStartTest(testerIndexTemp - 1, 1, sp2);
                            DateTime startTime = DateTime.Now;
                            TimeSpan ts = DateTime.Now - startTime;
                            //手动测试时强制复位治具结果
                            testerLogic.ResetResult();
                            //手动测试时强制治具有料，否则收不到结果
                            testerLogic.TesterTray.Helper.SetCellStatus(0, CellStatus.HasProduct);
                            testerLogic.TesterTray.Helper.SetCellStatus(1, CellStatus.HasProduct);
                            while (!testerLogic.AllEnabledTesterFinished() && ts.TotalMilliseconds < 60000)
                            {
                                ts = DateTime.Now - startTime;
                                Thread.Sleep(10);
                            }
                            if (ts.TotalMilliseconds >= 60000)
                            {
                                MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                return true;
                            }
                            this.BeginInvoke(new Action(() =>
                            {
                                int result1 = testerLogic.GetResult()[0] ? 1 : 0;
                                int result2 = testerLogic.GetResult()[1] ? 1 : 0;
                                label.Text = $"Tester{moduleIndexTemp}{t}";
                                label.Text += $":{result1},{result2}";
                                label.Enabled = true;
                                label.BackgroundStyle.BackColor = Color.DarkTurquoise;
                            }));
                        }
                    }
                }
                else if (bank1Status)
                {
                    bool ready1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 0);

                    if (!ready1Status)
                    {
                        MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                    }
                    else
                    {
                        bool loadStatus = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 0);

                        if (!loadStatus)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                        }
                        else
                        {
                            TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                            testerLogic.StartTest(testerIndexTemp - 1, 0, sn1, 0, out SendPackage sp1);
                            testerLogic.WaitStartTest(testerIndexTemp - 1, 0, sp1);
                            DateTime startTime = DateTime.Now;
                            TimeSpan ts = DateTime.Now - startTime;
                            //手动测试时强制复位治具结果
                            testerLogic.ResetResult();
                            //手动测试时强制治具有料，否则收不到结果
                            testerLogic.TesterTray.Helper.SetCellStatus(0, CellStatus.HasProduct);
                            while (!testerLogic.AllEnabledTesterFinished(0) && ts.TotalMilliseconds < 60000)
                            {
                                ts = DateTime.Now - startTime;
                                Thread.Sleep(10);
                            }
                            if (ts.TotalMilliseconds >= 60000)
                            {
                                MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                return true;
                            }
                            this.BeginInvoke(new Action(() =>
                            {
                                int result1 = testerLogic.GetResult()[0] ? 1 : 0;
                                int result2 = -1;
                                label.Text = $"Tester{moduleIndexTemp}{t}";
                                label.Text += $":{result1},{result2}";
                                label.Enabled = true;
                                label.BackgroundStyle.BackColor = Color.DarkTurquoise;
                            }));
                        }
                    }
                }
                else if (bank2Status)
                {
                    bool ready2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 1);

                    if (!ready2Status)
                    {
                        MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                    }
                    else
                    {
                        bool loadStatus2 = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 1, true);

                        if (!loadStatus2)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                        }
                        else
                        {
                            TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                            testerLogic.StartTest(testerIndexTemp - 1, 1, sn2, 0, out SendPackage sp2);
                            testerLogic.WaitStartTest(testerIndexTemp - 1, 1, sp2);
                            DateTime startTime = DateTime.Now;
                            TimeSpan ts = DateTime.Now - startTime;
                            //手动测试时强制复位治具结果
                            testerLogic.ResetResult();
                            //手动测试时强制治具有料，否则收不到结果
                            testerLogic.TesterTray.Helper.SetCellStatus(1, CellStatus.HasProduct);
                            while (!testerLogic.AllEnabledTesterFinished(1) && ts.TotalMilliseconds < 60000)
                            {
                                ts = DateTime.Now - startTime;
                                Thread.Sleep(10);
                            }
                            if (ts.TotalMilliseconds >= 60000)
                            {
                                MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                return true;
                            }
                            this.BeginInvoke(new Action(() =>
                            {
                                int result1 = -1;
                                int result2 = testerLogic.GetResult()[1] ? 1 : 0;
                                label.Text = $"Tester{moduleIndexTemp}{t}";
                                label.Text += $":{result1},{result2}";
                                label.Enabled = true;
                                label.BackgroundStyle.BackColor = Color.DarkTurquoise;
                            }));
                        }
                    }
                }
                return true;
            });
        }

        private void labelX9_Click(object sender, EventArgs e)
        {
            //GlobalVariable.TesterPC1.Connect();
            //labelX9.Enabled = false;
            List<LabelX> labels = new List<LabelX>();
            labels.Add(Tester11);
            labels.Add(Tester12);
            labels.Add(Tester13);
            labels.Add(Tester21);
            labels.Add(Tester22);
            labels.Add(Tester23);
            if (false)
            {
                Task.Run(() =>
                {
                    int moduleIndexTemp = 1;
                    int t = 1;
                    int testerIndexTemp = (moduleIndexTemp - 1) * 3 + t;

                    bool bank1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterEnabled(testerIndexTemp - 1, 0);
                    bool bank2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterEnabled(testerIndexTemp - 1, 1);

                    if (bank1Status && bank2Status)
                    {
                        bool ready1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 0);
                        bool ready2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 1);

                        if (!ready1Status || !ready2Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 0, true);
                            bool loadStatus2 = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 1, true);

                            if (!loadStatus || !loadStatus2)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 0, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}", 0, out SendPackage sp1);
                                testerLogic.StartTest(testerIndexTemp - 1, 1, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-2", 0, out SendPackage sp2);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 0, sp1);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 1, sp2);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(0, CellStatus.HasProduct);
                                testerLogic.TesterTray.Helper.SetCellStatus(1, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished() && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = testerLogic.GetResult()[0] ? 1 : 0;
                                    int result2 = testerLogic.GetResult()[1] ? 1 : 0;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    else if (bank1Status)
                    {
                        bool ready1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 0);

                        if (!ready1Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 0, true);

                            if (!loadStatus)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 0, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}", 0, out SendPackage sp1);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 0, sp1);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(0, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished(0) && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = testerLogic.GetResult()[0] ? 1 : 0;
                                    int result2 = -1;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    else if (bank2Status)
                    {
                        bool ready2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 1);

                        if (!ready2Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus2 = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 1, true);

                            if (!loadStatus2)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 1, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-2", 0, out SendPackage sp2);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 1, sp2);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(1, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished(1) && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = -1;
                                    int result2 = testerLogic.GetResult()[1] ? 1 : 0;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    return true;
                });
                Task.Run(() =>
                {
                    int moduleIndexTemp = 2;
                    int t = 1;
                    int testerIndexTemp = (moduleIndexTemp - 1) * 3 + t;

                    bool bank1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterEnabled(testerIndexTemp - 1, 0);
                    bool bank2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterEnabled(testerIndexTemp - 1, 1);

                    if (bank1Status && bank2Status)
                    {
                        bool ready1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 0);
                        bool ready2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 1);

                        if (!ready1Status || !ready2Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 0, true);
                            bool loadStatus2 = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 1, true);

                            if (!loadStatus || !loadStatus2)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 0, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}", 0, out SendPackage sp1);
                                testerLogic.StartTest(testerIndexTemp - 1, 1, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-2", 0, out SendPackage sp2);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 0, sp1);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 1, sp2);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(0, CellStatus.HasProduct);
                                testerLogic.TesterTray.Helper.SetCellStatus(1, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished() && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = testerLogic.GetResult()[0] ? 1 : 0;
                                    int result2 = testerLogic.GetResult()[1] ? 1 : 0;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    else if (bank1Status)
                    {
                        bool ready1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 0);

                        if (!ready1Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 0, true);

                            if (!loadStatus)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 0, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}", 0, out SendPackage sp1);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 0, sp1);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(0, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished(0) && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = testerLogic.GetResult()[0] ? 1 : 0;
                                    int result2 = -1;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    else if (bank2Status)
                    {
                        bool ready2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 1);

                        if (!ready2Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus2 = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 1, true);

                            if (!loadStatus2)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 1, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-2", 0, out SendPackage sp2);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 1, sp2);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(1, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished(1) && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = -1;
                                    int result2 = testerLogic.GetResult()[1] ? 1 : 0;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    return true;
                });
                Task.Run(() =>
                {
                    int moduleIndexTemp = 1;
                    int t = 2;
                    int testerIndexTemp = (moduleIndexTemp - 1) * 3 + t;

                    bool bank1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterEnabled(testerIndexTemp - 1, 0);
                    bool bank2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterEnabled(testerIndexTemp - 1, 1);

                    if (bank1Status && bank2Status)
                    {
                        bool ready1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 0);
                        bool ready2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 1);

                        if (!ready1Status || !ready2Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 0, true);
                            bool loadStatus2 = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 1, true);

                            if (!loadStatus || !loadStatus2)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 0, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}", 0, out SendPackage sp1);
                                testerLogic.StartTest(testerIndexTemp - 1, 1, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-2", 0, out SendPackage sp2);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 0, sp1);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 1, sp2);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(0, CellStatus.HasProduct);
                                testerLogic.TesterTray.Helper.SetCellStatus(1, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished() && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = testerLogic.GetResult()[0] ? 1 : 0;
                                    int result2 = testerLogic.GetResult()[1] ? 1 : 0;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    else if (bank1Status)
                    {
                        bool ready1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 0);

                        if (!ready1Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 0, true);

                            if (!loadStatus)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 0, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}", 0, out SendPackage sp1);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 0, sp1);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(0, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished(0) && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = testerLogic.GetResult()[0] ? 1 : 0;
                                    int result2 = -1;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    else if (bank2Status)
                    {
                        bool ready2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 1);

                        if (!ready2Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus2 = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 1, true);

                            if (!loadStatus2)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 1, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-2", 0, out SendPackage sp2);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 1, sp2);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(1, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished(1) && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = -1;
                                    int result2 = testerLogic.GetResult()[1] ? 1 : 0;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    return true;
                });
                Task.Run(() =>
                {
                    int moduleIndexTemp = 2;
                    int t = 2;
                    int testerIndexTemp = (moduleIndexTemp - 1) * 3 + t;

                    bool bank1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterEnabled(testerIndexTemp - 1, 0);
                    bool bank2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterEnabled(testerIndexTemp - 1, 1);

                    if (bank1Status && bank2Status)
                    {
                        bool ready1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 0);
                        bool ready2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 1);

                        if (!ready1Status || !ready2Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 0, true);
                            bool loadStatus2 = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 1, true);

                            if (!loadStatus || !loadStatus2)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 0, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}", 0, out SendPackage sp1);
                                testerLogic.StartTest(testerIndexTemp - 1, 1, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-2", 0, out SendPackage sp2);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 0, sp1);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 1, sp2);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(0, CellStatus.HasProduct);
                                testerLogic.TesterTray.Helper.SetCellStatus(1, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished() && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = testerLogic.GetResult()[0] ? 1 : 0;
                                    int result2 = testerLogic.GetResult()[1] ? 1 : 0;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    else if (bank1Status)
                    {
                        bool ready1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 0);

                        if (!ready1Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 0);

                            if (!loadStatus)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 0, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}", 0, out SendPackage sp1);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 0, sp1);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(0, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished(0) && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = testerLogic.GetResult()[0] ? 1 : 0;
                                    int result2 = -1;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    else if (bank2Status)
                    {
                        bool ready2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 1);

                        if (!ready2Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus2 = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 1);

                            if (!loadStatus2)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 1, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-2", 0, out SendPackage sp2);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 1, sp2);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(1, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished(1) && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = -1;
                                    int result2 = testerLogic.GetResult()[1] ? 1 : 0;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    return true;
                });
                Task.Run(() =>
                {
                    int moduleIndexTemp = 1;
                    int t = 3;
                    int testerIndexTemp = (moduleIndexTemp - 1) * 3 + t;

                    bool bank1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterEnabled(testerIndexTemp - 1, 0);
                    bool bank2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterEnabled(testerIndexTemp - 1, 1);

                    if (bank1Status && bank2Status)
                    {
                        bool ready1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 0);
                        bool ready2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 1);

                        if (!ready1Status || !ready2Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 0);
                            bool loadStatus2 = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 1);

                            if (!loadStatus || !loadStatus2)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 0, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}", 0, out SendPackage sp1);
                                testerLogic.StartTest(testerIndexTemp - 1, 1, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-2", 0, out SendPackage sp2);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 0, sp1);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 1, sp2);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(0, CellStatus.HasProduct);
                                testerLogic.TesterTray.Helper.SetCellStatus(1, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished() && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = testerLogic.GetResult()[0] ? 1 : 0;
                                    int result2 = testerLogic.GetResult()[1] ? 1 : 0;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    else if (bank1Status)
                    {
                        bool ready1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 0);

                        if (!ready1Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 0);

                            if (!loadStatus)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 0, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}", 0, out SendPackage sp1);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 0, sp1);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(0, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished(0) && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = testerLogic.GetResult()[0] ? 1 : 0;
                                    int result2 = -1;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    else if (bank2Status)
                    {
                        bool ready2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 1);

                        if (!ready2Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus2 = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 1);

                            if (!loadStatus2)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 1, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-2", 0, out SendPackage sp2);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 1, sp2);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(1, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished(1) && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = -1;
                                    int result2 = testerLogic.GetResult()[1] ? 1 : 0;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    return true;
                });
                Task.Run(() =>
                {
                    int moduleIndexTemp = 2;
                    int t = 3;
                    int testerIndexTemp = (moduleIndexTemp - 1) * 3 + t;

                    bool bank1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterEnabled(testerIndexTemp - 1, 0);
                    bool bank2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterEnabled(testerIndexTemp - 1, 1);

                    if (bank1Status && bank2Status)
                    {
                        bool ready1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 0);
                        bool ready2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 1);

                        if (!ready1Status || !ready2Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 0);
                            bool loadStatus2 = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 1);

                            if (!loadStatus || !loadStatus2)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 0, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}", 0, out SendPackage sp1);
                                testerLogic.StartTest(testerIndexTemp - 1, 1, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-2", 0, out SendPackage sp2);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 0, sp1);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 1, sp2);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(0, CellStatus.HasProduct);
                                testerLogic.TesterTray.Helper.SetCellStatus(1, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished() && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = testerLogic.GetResult()[0] ? 1 : 0;
                                    int result2 = testerLogic.GetResult()[1] ? 1 : 0;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    else if (bank1Status)
                    {
                        bool ready1Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 0);

                        if (!ready1Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 0, true);

                            if (!loadStatus)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 0, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}", 0, out SendPackage sp1);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 0, sp1);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(0, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished(0) && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = testerLogic.GetResult()[0] ? 1 : 0;
                                    int result2 = -1;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    else if (bank2Status)
                    {
                        bool ready2Status = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).IsTesterReady(testerIndexTemp - 1, 1);

                        if (!ready2Status)
                        {
                            MessageBox.Show($"治具{testerIndexTemp}气缸状态异常!");
                        }
                        else
                        {
                            bool loadStatus2 = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic).OpenVac(testerIndexTemp - 1, 1, true);

                            if (!loadStatus2)
                            {
                                MessageBox.Show($"治具{testerIndexTemp}开真空异常!");
                            }
                            else
                            {
                                TesterLogic testerLogic = (FlowManager.Instance.SelectFlow($"测试模组{moduleIndexTemp}{t}") as TesterLogic);
                                testerLogic.StartTest(testerIndexTemp - 1, 1, $"VSN{DateTime.Now.ToString("yyyyMMddHHmmssfff")}-2", 0, out SendPackage sp2);
                                testerLogic.WaitStartTest(testerIndexTemp - 1, 1, sp2);
                                DateTime startTime = DateTime.Now;
                                TimeSpan ts = DateTime.Now - startTime;
                                //手动测试时强制复位治具结果
                                testerLogic.ResetResult();
                                //手动测试时强制治具有料，否则收不到结果
                                testerLogic.TesterTray.Helper.SetCellStatus(1, CellStatus.HasProduct);
                                while (!testerLogic.AllEnabledTesterFinished(1) && ts.TotalMilliseconds < 60000)
                                {
                                    ts = DateTime.Now - startTime;
                                    Thread.Sleep(10);
                                }
                                if (ts.TotalMilliseconds >= 60000)
                                {
                                    MessageBox.Show($"等待测试测试模组{testerIndexTemp}测试完成超时!", "系统");
                                    return true;
                                }
                                this.BeginInvoke(new Action(() =>
                                {
                                    int result1 = -1;
                                    int result2 = testerLogic.GetResult()[1] ? 1 : 0;
                                    labels[testerIndexTemp - 1].Text = $"Tester{moduleIndexTemp}{t}";
                                    labels[testerIndexTemp - 1].Text += $":{result1},{result2}";
                                    labels[testerIndexTemp - 1].Enabled = true;
                                    labels[testerIndexTemp - 1].BackgroundStyle.BackColor = Color.DarkTurquoise;
                                }));
                            }
                        }
                    }
                    return true;
                });
            }
        }

        protected override bool ProcessDialogKey(Keys keycode)
        {
            switch (keycode)
            {
                case Keys.Space:
                    if (btn_Pause.Enabled)
                        btn_Pause.PerformClick();
                    break;
            }
            //return true;
            return base.ProcessDialogKey(keycode);
        }

        private void superTabControl1_SelectedTabChanged(object sender, SuperTabStripSelectedTabChangedEventArgs e)
        {
            SuperTabItem superTabItem = (sender as SuperTabControl)?.SelectedTab;
            if (null != superTabItem && superTabItem.Name.Equals("sT_WorkSetting"))
            {
                lbl_CurOPID.Text = SystemConfig.Instance.MesParam.OPID;
            }
        }

        private void btn_RefershOPID_Click(object sender, EventArgs e)
        {
            lbl_CurOPID.Text = SystemConfig.Instance.MesParam.OPID;
            SystemInfo.ShowToastInfo(this.superTabControl1, $"已刷新显示当前OPID!", false);
        }

        private void btn_UpdateOPID_Click(object sender, EventArgs e)
        {
            //tb_NewOPID.Text = "Operator005";
            if (!string.IsNullOrEmpty(tb_NewOPID.Text/*.ToString()*/))
            {
                try
                {
                    SystemConfig.Instance.MesParam.OPID = tb_NewOPID.Text;
                    SystemConfig.Instance.Save();
                }
                catch
                {
                    SystemInfo.ShowToastInfo(this.superTabControl1, $"更新OPID失败!请重试！", false);
                }
                SystemInfo.ShowToastInfo(this.superTabControl1, $"已更新OPID!", false);
                UpdateMesOPID?.Invoke();
            }
            else
            {
                SystemInfo.ShowToastInfo(this.superTabControl1, $"OPID不能为空!", false);
            }

        }

        public void ResetSignalToPLC()
        {
            //复位上料
            GlobalVariable.PCWritePLCData[(int)EnumHelper.GetEnumValueFromDescription<PLCOutFlag>("需上料满Tray")] = false;
            GlobalVariable.PCWritePLCData[(int)EnumHelper.GetEnumValueFromDescription<PLCOutFlag>("需上料满Tray2")] = false;
            GlobalVariable.PCWritePLCData[(int)EnumHelper.GetEnumValueFromDescription<PLCOutFlag>("取上料满Tray完成")] = false;
            GlobalVariable.PCWritePLCData[(int)EnumHelper.GetEnumValueFromDescription<PLCOutFlag>("取上料满Tray完成2")] = false;
            //复位下料
            GlobalVariable.PCWritePLCData[(int)EnumHelper.GetEnumValueFromDescription<PLCOutFlag>("需下料空Tray")] = false;
            GlobalVariable.PCWritePLCData[(int)EnumHelper.GetEnumValueFromDescription<PLCOutFlag>("需下料空Tray2")] = false;
            GlobalVariable.PCWritePLCData[(int)EnumHelper.GetEnumValueFromDescription<PLCOutFlag>("放下料空Tray完成")] = false;
            GlobalVariable.PCWritePLCData[(int)EnumHelper.GetEnumValueFromDescription<PLCOutFlag>("放下料空Tray完成2")] = false;
        }

        public bool NotifyRobotSwitchProduct(string sendString, out bool switchResult)
        {
            bool resulOut = false;
            switchResult = resulOut;
            CommunicationHelper robotHelper1 = new CommunicationHelper("Robot1", MachineResource.Instance.MachineTcpClient[$"机械手1"]);
            robotHelper1.Connect();
            SendPackage sp = new SendPackage() { Message = $"{sendString}\r\n" };
            Task t1 = Task.Run(() =>
            {
            reSend:
                if (GlobalVariable.RobotStatus[(int)RobotinEnumRobot1.机器人警报状态])
                {
                    GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人报警复位] = true;
                }
                GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人停止] = true;
                Thread.Sleep(50);
                GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人程序启动] = true;
                GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人程序启动] = true;
                robotHelper1.Send(sp);
                while (!sp.SendFlag && !FlowManager.Instance.IsBreak())
                {
                    Thread.Sleep(20);
                }
                GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人停止] = false;
                Thread.Sleep(200);
                GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人停止] = true;
                Thread.Sleep(50);
                GlobalVariable.RobotControlStatus[(int)RobotoutEnumRobot1.机器人程序启动] = false;
                if (string.IsNullOrEmpty(sp.RecvStr) || !sp.RecvStr.Contains("SwitchProduct"))
                {
                    if (sp.RecvStr.Contains("Welcome"))
                    {
                        goto reSend;
                    }
                    MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Warn, $"通知机械手切换产品接收超时！", "切换产品", 0, "切换产品"));
                    FlowManager.Instance.Pause();
                    if (MessageBox.Show("通知机械手切换产品接收超时，即将重试", "机械手切换产品", MessageBoxButtons.RetryCancel, MessageBoxIcon.Question) == DialogResult.Retry)
                    {
                        MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, $"重新通知机械手切换产品", "切换产品", 0, "切换产品"));
                        goto reSend;
                    }
                    else
                    {
                        resulOut = false;
                    }
                }
                else
                {
                    MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, $"收到机械手1消息：{sp.RecvStr}", "切换产品", 0, "切换产品"));
                    if (sp.RecvStr.Contains("SwitchProduct") && sp.RecvStr.Contains("OK"))
                    {
                        resulOut = true;
                    }
                    else
                    {
                        MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Warn, $"通知机械手切换产品接收超时！", "切换产品", 0, "切换产品"));
                        FlowManager.Instance.Pause();
                        if (MessageBox.Show("根据当前配方，即将通知机械手切换为 厚 ", "机械手切换产品", MessageBoxButtons.RetryCancel, MessageBoxIcon.Question) == DialogResult.Retry)
                        {
                            MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, $"重新通知机械手切换产品", "切换产品", 0, "切换产品"));
                            goto reSend;
                        }
                        else
                        {
                            resulOut = false;
                        }
                    }
                }
            });
            Task.WaitAll(t1);
            switchResult = resulOut;
            return true;
        }

        public void ReceiveRobotSwitchProduct(string recvString)
        {

        }

        private void lbl_SendToRBT_Click(object sender, EventArgs e)
        {
            string sendString = "SwitchProduct,Thin";
            CommunicationHelper robotHelper1 = new CommunicationHelper("Robot1", MachineResource.Instance.MachineTcpClient[$"机械手1"]);
            SendPackage sp = new SendPackage() { Message = $"{sendString}\r\n" };
            robotHelper1.Send(sp);
            Task.Run(() =>
            {
                while (!sp.SendFlag)
                {
                    Thread.Sleep(20);
                }
                if (lbl_RecvToRBT.InvokeRequired)
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        lbl_RecvToRBT.Text = sp.RecvStr.Replace("\r\n", "");
                    }));
                }
                else
                {
                    lbl_RecvToRBT.Text = sp.RecvStr.Replace("\r\n", "");
                }
            });

        }

        private void button1_Click_6(object sender, EventArgs e)
        {
            ModbusTcp tcp = new ModbusTcp("192.168.10.31", 502);
            tcp.Connect();

            tcp.ReadShort("400", 20, out short[] data);
        }

        private void button1_Click_7(object sender, EventArgs e)
        {
            //MachineResource.Instance.MachineAxis["测试移载线1左轴"].SetChangeSpeed(5, 0.2);
            //MachineResource.Instance.MachineAxis["测试移载线1左轴"].SetSpeed(SpeedType.Manual);
            //MachineResource.Instance.MachineAxis["测试移载线1左轴"].MoveAbsolute(100, out string stopReason, 1, true, 200);
        }

        public void MesSendSts(bool enable)
        {
            if (!SystemConfig.Instance.UsingStatus.IsFrontDisable)
            {
                if (MachineResource.Instance.MachineTcpClient.ContainsKey("一键熄屏1"))
                {
                    TCPClient client = MachineResource.Instance.MachineTcpClient["一键熄屏1"];
                    if (!client.IsConnected)
                        client.Connect();
                    string str = $"Mes,{(enable ? "enable" : "disenable")}\r\n";
                    client.Send(str);
                    MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, $"PC-->Tester1:{str}", "系统", 0, "系统"));
                }
            }
            if (!SystemConfig.Instance.UsingStatus.IsBackDisable)
            {
                if (MachineResource.Instance.MachineTcpClient.ContainsKey("一键熄屏2"))
                {
                    TCPClient client = MachineResource.Instance.MachineTcpClient["一键熄屏2"];
                    if (!client.IsConnected)
                        client.Connect();
                    string str = $"Mes,{(enable ? "enable" : "disenable")}\r\n";
                    client.Send(str);
                    MachineMessageScheduler.Instance.Add(new MachineMessage(MessageType.Log, $"PC-->Tester2:{str}", "系统", 0, "系统"));
                }
            }
        }

        bool status = false;
        private async void labelX13_Click(object sender, EventArgs e)
        {
            labelX13.Enabled = false;
            labelX13.Enabled = await Task.Run(() =>
            {
                List<Cylinder> nozzles = new List<Cylinder>()
                {
                    MachineResource.Instance.MachineCylinder["上料移载取料气缸1下降V"],
                    MachineResource.Instance.MachineCylinder["上料移载取料气缸2下降V"],
                    MachineResource.Instance.MachineCylinder["上料移载取料气缸3下降V"],
                    MachineResource.Instance.MachineCylinder["上料移载取料气缸4下降V"],
                };

                status = !status;
                if(status)
                    nozzles.ForEach(n => n.On());
                else
                    nozzles.ForEach(n => n.Off());

                Thread.Sleep(1000);

                return true;
            });
        }

        bool status2 = false;
        private async void labelX14_Click(object sender, EventArgs e)
        {
            labelX14.Enabled = false;
            labelX14.Enabled = await Task.Run(() =>
            {
                List<Cylinder> nozzles = new List<Cylinder>()
                {
                    MachineResource.Instance.MachineCylinder["测试移载取料气缸1下降V"],
                    MachineResource.Instance.MachineCylinder["测试移载取料气缸2下降V"],
                    MachineResource.Instance.MachineCylinder["测试移载取料气缸3下降V"],
                    MachineResource.Instance.MachineCylinder["测试移载取料气缸4下降V"],
                };

                status2 = !status2;
                if (status2)
                    nozzles.ForEach(n => n.On());
                else
                    nozzles.ForEach(n => n.Off());

                Thread.Sleep(1000);

                return true;
            });
        }

        bool status3 = false;
        private async void labelX15_Click(object sender, EventArgs e)
        {
            labelX15.Enabled = false;
            labelX15.Enabled = await Task.Run(() =>
            {
                List<Cylinder> nozzles = new List<Cylinder>()
                {
                    MachineResource.Instance.MachineCylinder["下料移载取料气缸1下降V"],
                    MachineResource.Instance.MachineCylinder["下料移载取料气缸2下降V"],
                    MachineResource.Instance.MachineCylinder["下料移载取料气缸3下降V"],
                    MachineResource.Instance.MachineCylinder["下料移载取料气缸4下降V"],
                };

                status3 = !status3;
                if (status3)
                    nozzles.ForEach(n => n.On());
                else
                    nozzles.ForEach(n => n.Off());

                Thread.Sleep(1000);

                return true;
            });
        }
    }
}
